Skip to content

[Hyun] Week 1 Solutions #26

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Apr 28, 2024
Merged

[Hyun] Week 1 Solutions #26

merged 6 commits into from
Apr 28, 2024

Conversation

WhiteHyun
Copy link
Member

@WhiteHyun WhiteHyun commented Apr 26, 2024

1. Two Sum

시간복잡도 $O(n^2)$로도 충분히 풀 수 있는 문제입니다.
시간복잡도 $O(n\log n)$로도 가능하리라 생각하여 정렬 후 투 포인터를 사용해서 구현해보았습니다..

근데 $O(n)$으로도 가능하더라고요. 😅

121. Best Time to Buy and Sell Stock

최소한의 가격으로 구매하고 최대한의 이익을 내는 문제입니다.
투 포인터로 구현했습니다.
leftright를 두고 right를 증가시켜 최대한의 차이를 저장하다가, right 위치의 값이 left위치의 값보다 저렴한 축에 속하는 경우 left의 값을 right로 두고 다시 반복문을 진행했습니다.

Time Complexity: $O(N)$

125. Valid Palindrome

특수문자와 숫자가 들어가는 것을 유념하고 풀어야하는 문제입니다.
Swift에서는 Regex String이라는 것이 있어 아래와 같이 정규식을 사용할 수 있는데요.

for match in s.matches(of: /(?<alphabet>[a-zA-Z0-9]+)/) {
  // ...
}

컴파일 에러가 나서 리트코드 언어 환경를 확인해보니 Swift 5.9 버전임을 알 수 있었습니다만..

해당 Regex String은 5.9에서도 가능해야하는 일이라 좀 의아해서 Support & Feedback에 글을 남겨두었습니다.

아무튼 다른 방법의 Regex를 사용하는 방법으로 구현했습니다.

217. Contains Duplicate

중복되는 값이 있다면 true, 아니면 false를 리턴하는 문제입니다.

Set으로 만든 후에 길이가 같은지 아닌지로 판단해서 구현했습니다.

Time Complexity: $O(N)$

242. Valid Anagram

약간 Swift Dictionary initializer를 이용해서 풀이했기에 이해가 잘 안가는 코드일 수도 있습니다. 하하

Dictionary(s.map { ($0, 1) }, uniquingKeysWith: +)

위 코드에 중에서 s.map { ($0, 1) }을 설명드리자면,
s라는 문자열에서 각 문자와 숫자 1을 튜플로 매핑하여 값을 만듭니다. 만약 abcd라면 [("a", 1), ("b", 1), ("c", 1), ("d", 1)]이 됩니다.
그리고 Dictionary(_:uniquingKeysWith:) initializer에서 마지막 인자(uniquingKeysWith)로 클로저를 사용해야 하며, 이 클로저로 딕셔너리의 값을 저장하게 되는데요. +자체가 Swift에서는 (Int, Int) -> Int 타입의 클로저이기 때문에 별도의 구현 없이 +기호를 그대로 넣을 수 있습니다. 이렇게 되면 튜플의 첫 번째 값을 key로 하고 두 번째 값을 덧셈하여 저장할 수 있게 됩니다.

따라서 해당 Dictionary는 다음과 같은 값을 가집니다.

  • s"abcd"인 경우: {"a": 1, "b": 1, "c": 1, "d": 1}
  • s"abcdeab"인 경우: {"a": 2, "b": 2, "c": 1, "d": 1, "e": 1}

이 initializer를 이용하여 s와 t의 각 문자당 빈도수를 구한 뒤 서로 동일한지를 체크하여 구현했습니다.

Time Complexity: $O(N)$

@WhiteHyun
Copy link
Member Author

AssigneesReviewers는 권한이 없어 설정하지 못하는 점 양해 부탁드립니다. 🙇

@DaleSeo
Copy link
Member

DaleSeo commented Apr 26, 2024

AssigneesReviewers는 권한이 없어 설정하지 못하는 점 양해 부탁드립니다. 🙇

제가 해드렸습니다. 이 부분은 코드 작성자나 저장소 관리자가 직접 할 필요없도록 빠른 시일 내로 자동화하도록 하겠습니다.

import Foundation

final class LeetCode217 {
func containsDuplicate(_ nums: [Int]) -> Bool {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

폴더 이름과 답안 코드가 불일치하는 것 같습니다.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

스크립트로 파일을 생성하면서 생긴 이슈인 것 같습니다. (문제를 풀 때 자동완성 스크립트를 쓰고 있습니다).
LeetCode217 대신에 Solution이라는 이름으로 변경하면 제출가능하실 겁니다!
저도 모든 파일을 Solution이라는 이름으로 수정해서 다시 커밋 남기겠습니다. 감사합니다!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

그 부분보다는 답안이 서로 바뀐것 같아요~
contains duplicate랑 best time to buy amd sell 이랑요

Copy link
Member Author

@WhiteHyun WhiteHyun Apr 27, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

제가 이해를 잘못했군요. 😅
확인해보고 고치겠습니다! 감사합니다 🙇🙇

@DaleSeo
Copy link
Member

DaleSeo commented Apr 27, 2024

시간복잡도
𝑂
(
𝑛
2
)
로도 충분히 풀 수 있는 문제입니다.

마크다운에서 $ 기호를 이렇게 활용할 수 있는지 몰랐습니다! 🤯


final class LeetCode242 {
func isAnagram(_ s: String, _ t: String) -> Bool {
Dictionary(s.map { ($0, 1) }, uniquingKeysWith: +) == Dictionary(t.map { ($0, 1) }, uniquingKeysWith: +)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR에 친절하게 설명해주셔서 이 코드를 가까스로 이해했네요 ㅋㅋ
면접관이 Swfit를 쓰는지 여부에 따라서 이런 코드는 호불호가 갈릴 수도 있겠다는 생각이 들었습니다.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

다음부터는 숏코딩 보다는 읽기 쉬운 코드로 변경해보겠습니다.
조언 감사드립니다. 🙇

@DaleSeo
Copy link
Member

DaleSeo commented Apr 27, 2024

해당 Regex String은 5.9에서도 가능해야하는 일이라 좀 의아해서 Support & Feedback에 글을 남겨두었습니다.

호기심에 링크를 클릭해봤는데 아래와 같이 나오네요? 작성자만 볼 수 있나봅니다.

Shot 2024-04-26 at 22 14 12@2x

@WhiteHyun
Copy link
Member Author

해당 Regex String은 5.9에서도 가능해야하는 일이라 좀 의아해서 Support & Feedback에 글을 남겨두었습니다.

호기심에 링크를 클릭해봤는데 아래와 같이 나오네요? 작성자만 볼 수 있나봅니다.

Shot 2024-04-26 at 22 14 12@2x


방금 확인해보았는데, 시크릿모드로 들어가니 제 글이 안보이네요.. 공개 설정하는 란도 없어보여서 제 의견이 누구한테도 보이지 않는 것 같군요.
슬프네요 😂😂

@WhiteHyun WhiteHyun requested a review from DaleSeo April 27, 2024 13:49
Copy link
Member

@DaleSeo DaleSeo left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

답안 코드 제출 감사합니다. Swift 쓰시는 분들에게 도움이 되겠네요.

@DaleSeo DaleSeo added this to the week1 milestone Apr 28, 2024
@DaleSeo DaleSeo merged commit 2ab3667 into DaleStudy:main Apr 28, 2024
@DaleSeo DaleSeo mentioned this pull request Apr 28, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
No open projects
Status: Done
Development

Successfully merging this pull request may close these issues.

3 participants