diff --git a/contains-duplicate/wlghsp.py b/contains-duplicate/wlghsp.py new file mode 100644 index 0000000000..7f23dd94f5 --- /dev/null +++ b/contains-duplicate/wlghsp.py @@ -0,0 +1,7 @@ +""" + * Time Complexity: O(N) + * Space Complexity: O(N) +""" +class Solution: + def containsDuplicate(self, nums: list[int]) -> bool: + return len(set(nums)) != len(nums) diff --git a/house-robber/wlghsp.py b/house-robber/wlghsp.py new file mode 100644 index 0000000000..6d46f94cb0 --- /dev/null +++ b/house-robber/wlghsp.py @@ -0,0 +1,20 @@ +""" + * Time Complexity: O(N) + * Space Complexity: O(N) +""" +class Solution: + def rob(self, nums: list[int]) -> int: + n = len(nums) + + if n == 1: + return nums[0] + + # dp[i]: 0번 부터 i번째 집까지 고려했을 때 얻을 수 있는 최대 금액 + dp = [0] * n + dp[0] = nums[0] + dp[1] = max(nums[0], nums[1]) + + for i in range(2, n): + dp[i] = max(dp[i - 2] + nums[i], dp[i - 1]) + + return dp[-1] diff --git a/longest-consecutive-sequence/wlghsp.py b/longest-consecutive-sequence/wlghsp.py new file mode 100644 index 0000000000..273a5f2825 --- /dev/null +++ b/longest-consecutive-sequence/wlghsp.py @@ -0,0 +1,15 @@ +""" + * Time Complexity: O(N) + * Space Complexity: O(N) +""" +class Solution: + def longestConsecutive(self, nums: list[int]) -> int: + nums_set = set(nums) + ans = 0 + for n in nums_set: + if (n - 1) not in nums_set: + length = 1 + while n + length in nums_set: + length += 1 + ans = max(length, ans) + return ans diff --git a/top-k-frequent-elements/wlghsp.py b/top-k-frequent-elements/wlghsp.py new file mode 100644 index 0000000000..75edb6a64a --- /dev/null +++ b/top-k-frequent-elements/wlghsp.py @@ -0,0 +1,24 @@ +""" + * Time Complexity: O(n) + * Space Complexity: O(n) +""" +from collections import Counter +class Solution: + def topKFrequent(self, nums: list[int], k: int) -> list[int]: + # 1. 빈도 계산: O(N) + count = Counter(nums) + + # 2. 빈도를 인덱스로 사용하는 버킷 배열 생성: O(N) + # 최대 빈도는 len(nums)이므로 크기는 len(nums) + 1 + buckets = [[] for _ in range(len(nums) + 1)] + for num, freq in count.items(): + buckets[freq].append(num) + + # 3. 높은 빈도(뒤쪽 인덱스)부터 k개 추출: O(N) + res = [] + for freq in range(len(buckets) - 1, 0, -1): + for num in buckets[freq]: + res.append(num) + if len(res) == k: + return res + return res diff --git a/two-sum/wlghsp.py b/two-sum/wlghsp.py new file mode 100644 index 0000000000..cbdd3fb7d3 --- /dev/null +++ b/two-sum/wlghsp.py @@ -0,0 +1,13 @@ +""" + * Time Complexity: O(N) + * Space Complexity: O(N) +""" +class Solution: + def twoSum(self, nums: list[int], target: int) -> list[int]: + num_dict = {} + for i, e in enumerate(nums): + other = target - e + if other in num_dict: + return [num_dict[other], i] + num_dict[e] = i + return []