-
-
Notifications
You must be signed in to change notification settings - Fork 304
[liza0525] WEEK 02 solutions #2064
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
+124
−0
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
a711b3e
week2 - valid anagram
liza0525 f60fca7
week2 - climbing-stiars
liza0525 42a7fa1
week2 - product of array except self
liza0525 9cb0d3f
week2 - 3sum
liza0525 b2e44a9
week2 - validate-binary-search-tree
liza0525 4e47240
Merge branch 'DaleStudy:main' into main
liza0525 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| class Solution: | ||
| # 해당 문제는 two point 알고리즘을 사용한다. 이 때 '정렬'을 해야 알고리즘을 정확하게 적용할 수 있다. | ||
| # 기준 값을 하나 정한 후, 그 값의 다음 인덱스부터 양 끝에 포인터를 두고 세 수의 합을 확인한다. | ||
| # 만약 수가 0보다 작으면, 더 큰 수를 더해야 하므로 작은 값 쪽 인덱스를 하나 올리고 | ||
| # 0보다 크면, 더 작은 수를 더해야 하므로 큰 쪽 값의 인덱스를 낮춘다. | ||
| def threeSum(self, nums: List[int]) -> List[List[int]]: | ||
| # nums를 정렬한 후 | ||
| nums.sort() | ||
| results = set() | ||
|
|
||
| for i in range(len(nums) - 2): | ||
| if nums[i] > 0: | ||
| # 정렬을 한 후의 가장 작은 수(i가 0일 때의 value)가 0보다 크다면, | ||
| # 리스트 내 모든 수가 0보다 크기 때문에 합이 0이 될 수 없으므로 만족하는 답이 없으니 break | ||
| break | ||
|
|
||
| if i > 0 and nums[i] == nums[i - 1]: | ||
| # 이전 인덱스의 값과 동일한 값이라면 동일한 계산을 반복한 것이므로 | ||
| # 중복 계산을 피하기 위해 넘어간다. | ||
| continue | ||
|
|
||
| # i 인덱스를 기준으로 오른쪽으로 포인터 설정 | ||
| left, right = i + 1, len(nums) - 1 | ||
|
|
||
| while left < right: | ||
| result = nums[i] + nums[left] + nums[right] | ||
| if result < 0: | ||
| # 합이 0보다 작으면 왼쪽 인덱스를 올린다 | ||
| left += 1 | ||
| elif result > 0: | ||
| # 합이 0보다 크면 오른쪽 인덱스를 내린다 | ||
| right -= 1 | ||
| else: # result == 0 | ||
| # 합이 0이면 답이 되므로 results에 추가하고 | ||
| # 포인터들을 조정한다. | ||
| results.add((nums[i], nums[left], nums[right])) | ||
| left, right = left + 1, right - 1 | ||
| return list(results) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| class Solution: | ||
| # n번째 계단에 오를 수 있는 방법 수는 (n - 1번째 계단에 오르는 방법 수) + (n - 2번째 계단에 오르는 방법 수)와 같다. | ||
| # 이는 피보나치 수열 공식에 기반하며, 피보나치 수열 상 n번째 오는 수가 곧 답이 된다. | ||
| def climbStairs(self, n: int) -> int: | ||
| memo = [1, 1, 2] | ||
|
|
||
| def fibonacci(step): | ||
| if step > n: | ||
| return | ||
|
|
||
| ways = memo[step - 1] + memo[step - 2] | ||
| memo.append(ways) | ||
| fibonacci(step + 1) | ||
|
|
||
| fibonacci(3) | ||
|
|
||
| return memo[n] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| class Solution: | ||
| def productExceptSelf(self, nums: List[int]) -> List[int]: | ||
| # 자기 자신을 제외한 모든 인덱스의 곱을 곱하는 건, 자기 자신 기준 왼쪽 인덱스들의 곱과 오른쪽 인덱스들의 곱을 최종적으로 곱한 것과 동일하다. | ||
| # answer[i]은 (i 기준 왼쪽 인덱스 값들의 누적 곱) * (i 기준 오른쪽 인덱스 값들의 누적 곱) | ||
| answers = [1 for _ in range(len(nums))] | ||
|
|
||
| # 여기서 before_total_prod는 인덱스 i 기준 왼쪽 인덱스들의 누적 곱 | ||
| # 즉, before_total_prod = nums[1] * num[2] * ... * num[i - 2] * num[i - 1] | ||
| before_total_prod = 1 | ||
| for i in range(1, len(nums)): | ||
| before_total_prod *= nums[i - 1] | ||
| answers[i] *= before_total_prod | ||
|
|
||
| # 여기서 after_total_prod는 인덱스 i 기준 오른쪽 인덱스들의 누적 곱 | ||
| # 즉, after_total_prod = nums[n - 1] * num[n - 2] * ... * num[i + 2] * num[i + 1] | ||
| # (n은 리스트 nums 의 길이, 구현은 n - 1 인덱스부터 거꾸로 계산) | ||
| after_total_prod = 1 | ||
| for i in range(len(nums) - 2, -1, -1): | ||
| after_total_prod *= nums[i + 1] | ||
| answers[i] *= after_total_prod | ||
|
|
||
| return answers |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| from collections import defaultdict | ||
|
|
||
|
|
||
| class Solution: | ||
| def isAnagram(self, s: str, t: str) -> bool: | ||
| # 1. s를 구성하고 있는 각 알파벳과 그 알파벳이 존재하는 개수를 세기 위해 | ||
| # defaultdict로 dictionary 만들어준다. | ||
| alphabet_cnt_dict = defaultdict(int) | ||
|
|
||
| # 2. s의 알파벳을 탐색하면서 alphabet_cnt_dict에서 count(value)를 하나씩 증가 | ||
| # 예시: anagram의 경우, {"a": 3, "n": 1, "g": 1, "m": 1, "r": 1}이 최종 값이 됨 | ||
| for ss in s: | ||
| alphabet_cnt_dict[ss] += 1 | ||
|
|
||
| # 3. t의 알파벳을 탐색하면서 alphabet_cnt_dict에서 count(value)를 하나씩 감소 | ||
| # 예시: anagram의 아나그램인 경우, {"a": 0, "n": 0, "g": 0, "m": 0, "r": 0}이 최종 값이 됨 | ||
| for tt in t: | ||
| alphabet_cnt_dict[tt] -= 1 | ||
|
|
||
| # 4. s와 t가 서로 아나그램이었다면, 구성했던 모든 알파벳에 대해 count 값이 0으로 변경되어 있어야 함 | ||
| # 그렇지 않으면(양수 또는 음수 값이 존재하면) 아나그램이라고 할 수 없다. | ||
| for cnt in alphabet_cnt_dict.values(): | ||
| if cnt != 0: | ||
| return False | ||
| return True |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| class Solution: | ||
| # 중위 순회를 한 결과를 리스트에 저장한 후, 그 결과 리스트 내 value들이 정렬이 되어 있는지 확인 | ||
| def isValidBST(self, root: Optional[TreeNode]) -> bool: | ||
| inorder_result_list = [] | ||
|
|
||
| def inorder_tree(tree_node): | ||
| if tree_node.left: | ||
| inorder_tree(tree_node.left) | ||
|
|
||
| inorder_result_list.append(tree_node.val) | ||
|
|
||
| if tree_node.right: | ||
| inorder_tree(tree_node.right) | ||
|
|
||
| inorder_tree(root) | ||
|
|
||
| for i in range(len(inorder_result_list) - 1): | ||
| # i + 1 인덱스 값보다 i + 1 인덱스의 값이 커야 한다. 아니면 False | ||
| if inorder_result_list[i] >= inorder_result_list[i + 1]: | ||
| return False | ||
|
|
||
| return True |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
안녕하세요!
inorder로 순회하는 중에 값을 비교하는 방법도 있을 것 같습니다!
주석뿐만아니라 코드 전체적으로 깔끔해서 읽기 편했어요!
문제 푸시느라 고생많으셨어요!💪
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
안녕하세요~ 리뷰 감사합니다!
말씀하신대로 순회하면서 값 비교 해보는 것도 한 번 시도해봐야겠네요! 좋은 인사이트 감사드려요😊