-
-
Notifications
You must be signed in to change notification settings - Fork 245
[EGON] Week 01 Solutions #322
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
Changes from 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
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,60 @@ | ||
from unittest import TestCase, main | ||
from typing import List | ||
from collections import Counter | ||
|
||
|
||
class Solution: | ||
def containsDuplicate(self, nums: List[int]) -> bool: | ||
return self.solve_3(nums=nums) | ||
|
||
""" | ||
Runtime: 412 ms (Beats 75.17%) | ||
Analyze Complexity: O(n) | ||
Memory: 31.92 MB (Beats 45.93%) | ||
""" | ||
def solve_1(self, nums: List[int]) -> bool: | ||
return len(nums) != len(set(nums)) | ||
|
||
""" | ||
Runtime: 423 ms (Beats 39.66%) | ||
Analyze Complexity: O(n) | ||
Memory: 34.54 MB (Beats 14.97%) | ||
""" | ||
def solve_2(self, nums: List[int]) -> bool: | ||
counter = {} | ||
for num in nums: | ||
if num in counter: | ||
return True | ||
else: | ||
counter[num] = True | ||
else: | ||
return False | ||
|
||
""" | ||
Runtime: 441 ms (Beats 16.59%) | ||
Analyze Complexity: O(n) | ||
Memory: 34.57 MB (Beats 14.97%) | ||
""" | ||
def solve_3(self, nums: List[int]) -> bool: | ||
return Counter(nums).most_common(1)[0][1] > 1 | ||
|
||
|
||
class _LeetCodeTCs(TestCase): | ||
def test_1(self): | ||
nums = [1, 2, 3, 1] | ||
output = True | ||
self.assertEqual(Solution.containsDuplicate(Solution(), nums=nums), output) | ||
|
||
def test_2(self): | ||
nums = [1, 2, 3, 4] | ||
output = False | ||
self.assertEqual(Solution.containsDuplicate(Solution(), nums=nums), output) | ||
|
||
def test_3(self): | ||
nums = [1, 1, 1, 3, 3, 4, 3, 2, 4, 2] | ||
output = True | ||
self.assertEqual(Solution.containsDuplicate(Solution(), nums=nums), output) | ||
|
||
|
||
if __name__ == '__main__': | ||
main() |
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,111 @@ | ||
from typing import Optional, List | ||
from unittest import TestCase, main | ||
from heapq import heappush, heappop | ||
|
||
|
||
class TreeNode: | ||
def __init__(self, val=0, left=None, right=None): | ||
self.val = val | ||
self.left = left | ||
self.right = right | ||
|
||
|
||
class Solution: | ||
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: | ||
return self.solve_2(root, k) | ||
|
||
""" | ||
Runtime: 50 ms (Beats 25.03%) | ||
Analyze Complexity: O(n) | ||
Memory: 19.55 MB (Beats 15.91%) | ||
""" | ||
def solve_1(self, root: Optional[TreeNode], k: int) -> int: | ||
visited = [] | ||
stack = [root] | ||
while stack: | ||
curr_node = stack.pop() | ||
heappush(visited, curr_node.val) | ||
if curr_node.left is not None: | ||
stack.append(curr_node.left) | ||
if curr_node.right is not None: | ||
stack.append(curr_node.right) | ||
|
||
result = visited[0] | ||
for _ in range(k): | ||
result = heappop(visited) | ||
|
||
return result | ||
|
||
""" | ||
Runtime: 43 ms (Beats 69.91%) | ||
Analyze Complexity: O(n) | ||
Memory: 19.46 MB (Beats 60.94%) | ||
""" | ||
def solve_2(self, root: Optional[TreeNode], k: int) -> int: | ||
vals = [] | ||
|
||
def inorder_traverse(root: Optional[TreeNode]): | ||
if root is None: | ||
return | ||
|
||
if len(vals) >= k: | ||
return | ||
Comment on lines
+51
to
+52
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 이 조건으로 빠르게 탐색을 마칠 수 있어 정말 좋네요! 👍 |
||
|
||
inorder_traverse(root.left) | ||
vals.append(root.val) | ||
inorder_traverse(root.right) | ||
|
||
inorder_traverse(root) | ||
return vals[k - 1] | ||
|
||
|
||
class _LeetCodeTCs(TestCase): | ||
def test_1(self): | ||
root = TreeNode( | ||
val=3, | ||
left=TreeNode( | ||
val=1, | ||
left=None, | ||
right=TreeNode( | ||
val=2, | ||
left=None, | ||
right=None, | ||
) | ||
), | ||
right=TreeNode( | ||
val=4, | ||
left=None, | ||
right=None | ||
) | ||
) | ||
|
||
k = 1 | ||
output = 1 | ||
self.assertEqual(Solution.kthSmallest(Solution(), root, k), output) | ||
|
||
def test_2(self): | ||
root = TreeNode( | ||
val=5, | ||
left=TreeNode( | ||
val=3, | ||
left=TreeNode( | ||
val=2, | ||
left=TreeNode( | ||
val=1 | ||
) | ||
), | ||
right=TreeNode( | ||
val=4 | ||
) | ||
), | ||
right=TreeNode( | ||
val=6 | ||
) | ||
) | ||
k = 3 | ||
output = [3] | ||
self.assertEqual(Solution.kthSmallest(Solution(), root, k), output) | ||
|
||
|
||
if __name__ == '__main__': | ||
main() |
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,72 @@ | ||
from unittest import TestCase, main | ||
|
||
|
||
class Solution: | ||
def hammingWeight(self, n: int) -> int: | ||
return self.solve_4(n=n) | ||
|
||
""" | ||
Runtime: 26 ms (Beats 97.13%) | ||
Analyze Complexity: O(log n), bin(int)가 O(log(n)) | ||
Memory: 16.56 MB (Beats 22.67%) | ||
""" | ||
def solve_1(self, n: int) -> int: | ||
return bin(n).count('1') | ||
|
||
""" | ||
Runtime: 31 ms (Beats 85.00%) | ||
Analyze Complexity: O(log n) | ||
Memory: 16.60 MB (Beats 22.67%) | ||
""" | ||
def solve_2(self, n: int) -> int: | ||
hamming_weight = 0 | ||
while n: | ||
hamming_weight += n % 2 | ||
n = n >> 1 | ||
return hamming_weight | ||
|
||
""" | ||
Runtime: 30 ms (Beats 88.73%) | ||
Analyze Complexity: O(k), k는 2진수의 1의 갯수 (== O(log(n))) | ||
Memory: 16.56 MB (Beats 22.67%) | ||
""" | ||
# Brian Kernighan's Algorithm | ||
def solve_3(self, n: int) -> int: | ||
hamming_weight = 0 | ||
while n: | ||
n &= (n - 1) | ||
hamming_weight += 1 | ||
return hamming_weight | ||
|
||
""" | ||
Runtime: 36 ms (Beats 53.56%) | ||
Analyze Complexity: O(k), k는 2진수의 1의 갯수 (== O(log(n))) | ||
Memory: 16.55 MB (Beats 22.67%) | ||
""" | ||
def solve_4(self, n: int) -> int: | ||
hamming_weight = 0 | ||
while n: | ||
hamming_weight += n & 1 | ||
n >>= 1 | ||
return hamming_weight | ||
|
||
|
||
class _LeetCodeTCs(TestCase): | ||
def test_1(self): | ||
n = 11 | ||
output = 3 | ||
self.assertEqual(Solution.hammingWeight(Solution(), n=n), output) | ||
|
||
def test_2(self): | ||
n = 128 | ||
output = 1 | ||
self.assertEqual(Solution.hammingWeight(Solution(), n=n), output) | ||
|
||
def test_3(self): | ||
n = 2147483645 | ||
output = 30 | ||
self.assertEqual(Solution.hammingWeight(Solution(), n=n), output) | ||
|
||
|
||
if __name__ == '__main__': | ||
main() |
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,57 @@ | ||
from unittest import TestCase, main | ||
|
||
|
||
class Solution: | ||
def countSubstrings(self, s: str) -> int: | ||
return self.solve_2(s) | ||
|
||
""" | ||
Runtime: 776 ms (Beats 10.15%) | ||
Analyze Complexity: O(n ** 3), for * for * slicing | ||
Memory: 16.43 MB (Beats 73.44%) | ||
""" | ||
def solve_1(self, s: str) -> int: | ||
count = 0 | ||
for left in range(len(s)): | ||
for right in range(left, len(s)): | ||
substring = s[left: right + 1] | ||
count += substring == substring[::-1] | ||
|
||
return count | ||
|
||
""" | ||
Runtime: 373 ms (Beats 19.31%) | ||
Analyze Complexity: O(n ** 2) | ||
Memory: 25.15 MB (Beats 11.85%) | ||
""" | ||
def solve_2(self, s: str) -> int: | ||
dp = [[left == right for left in range(len(s))] for right in range(len(s))] | ||
count = len(s) | ||
|
||
for i in range(len(s) - 1): | ||
dp[i][i + 1] = s[i] == s[i + 1] | ||
count += dp[i][i + 1] | ||
|
||
for length in range(3, len(s) + 1): | ||
for left in range(len(s) - length + 1): | ||
right = left + length - 1 | ||
dp[left][right] = dp[left + 1][right - 1] and s[left] == s[right] | ||
count += dp[left][right] | ||
|
||
return count | ||
|
||
|
||
class _LeetCodeTCs(TestCase): | ||
def test_1(self): | ||
s = "abc" | ||
output = 3 | ||
self.assertEqual(Solution.countSubstrings(Solution(), s), output) | ||
|
||
def test_2(self): | ||
s = "aaa" | ||
output = 6 | ||
self.assertEqual(Solution.countSubstrings(Solution(), s), output) | ||
|
||
|
||
if __name__ == '__main__': | ||
main() |
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,74 @@ | ||
from collections import Counter | ||
from typing import List | ||
from unittest import TestCase, main | ||
|
||
|
||
class Solution: | ||
def topKFrequent(self, nums: List[int], k: int) -> List[int]: | ||
return self.solve_3(nums, k) | ||
|
||
""" | ||
Runtime: 82 ms (Beats 87.87%) | ||
Analyze Complexity: O(n log n) | ||
most_common의 정렬이 O(n log n) | ||
Memory: 21.13 MB (Beats 60.35%) | ||
""" | ||
def solve_1(self, nums: List[int], k: int) -> List[int]: | ||
return [key for key, value in Counter(nums).most_common(k)] | ||
|
||
""" | ||
Runtime: 88 ms (Beats 62.46%) | ||
Analyze Complexity: O(n log n) | ||
counter 생성에 O(n), 정렬에 O(n log n), slicing에 O(k) | ||
Memory: 21.17 MB (Beats 60.35%) | ||
""" | ||
def solve_2(self, nums: List[int], k: int) -> List[int]: | ||
counter = {} | ||
for num in nums: | ||
counter[num] = 1 + counter.get(num, 0) | ||
|
||
sorted_counter = sorted(counter.items(), key=lambda item: -item[1]) | ||
return [item[0] for item in sorted_counter[:k]] | ||
|
||
|
||
""" | ||
Runtime: 81 ms (Beats 90.60%) | ||
Analyze Complexity: O(n) | ||
counter 생성이 O(n), counter_matrix 생성이 O(n), reversed는 O(1), early-return으로 O(k) | ||
Memory: 22.10 MB (Beats 12.57%) | ||
""" | ||
def solve_3(self, nums: List[int], k: int) -> List[int]: | ||
counter = {} | ||
for num in nums: | ||
counter[num] = 1 + counter.get(num, 0) | ||
|
||
counter_matrix = [[] for _ in range(len(nums) + 1)] | ||
for key, val in counter.items(): | ||
counter_matrix[val].append(key) | ||
|
||
result = [] | ||
for num_list in reversed(counter_matrix): | ||
for num in num_list: | ||
result.append(num) | ||
if len(result) >= k: | ||
return result | ||
else: | ||
return result | ||
|
||
|
||
class _LeetCodeTCs(TestCase): | ||
def test_1(self): | ||
nums = [1, 1, 1, 2, 2, 3] | ||
k = 2 | ||
output = [1, 2] | ||
self.assertEqual(Solution.topKFrequent(Solution(), nums, k), output) | ||
|
||
def test_2(self): | ||
nums = [1] | ||
k = 1 | ||
output = [1] | ||
self.assertEqual(Solution.topKFrequent(Solution(), nums, k), output) | ||
|
||
|
||
if __name__ == '__main__': | ||
main() |
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.
다양한 풀이로 하셔서 좋네요 :) 요부분 조금 궁금한게 있는데, bst의 heappush의 Time complexity가 제 기억엔 logn 이었던거로 기억하는데, 혹시 어떻게 n으로 도출하셨는지 알려주실수 있을까요?
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.
n개의 노드를 순회하며 각각 heap push를 하니 말씀하신 것 처럼 n * log n 이 맞습니다. 주석 복붙하다 빼먹은 것 같네요. 리뷰 감사합니다.