diff --git a/house-robber/sangbeenmoon.py b/house-robber/sangbeenmoon.py index 6b734a01c8..714ce00767 100644 --- a/house-robber/sangbeenmoon.py +++ b/house-robber/sangbeenmoon.py @@ -14,3 +14,29 @@ def rob(self, nums: List[int]) -> int: dp[i] = max(dp[i-2] + nums[i] , dp[i-1]) return dp[len(nums) - 1] + + + + + +# dp[i] = max(dp[i-1], dp[i-2] + num[i]) +# TC : O(n) +# SC : O(n) + +class Solution: + def rob(self, nums: List[int]) -> int: + dp = [0] * len(nums) + + dp[0] = nums[0] + + if len(nums) == 1: + return dp[0] + + dp[1] = max(nums[0],nums[1]) + + for i in range(2, len(nums)): + dp[i] = max(dp[i-1], dp[i-2] + nums[i]) + + return max(dp) + + diff --git a/longest-consecutive-sequence/sangbeenmoon.py b/longest-consecutive-sequence/sangbeenmoon.py index fa310273d9..334ad8b5f6 100644 --- a/longest-consecutive-sequence/sangbeenmoon.py +++ b/longest-consecutive-sequence/sangbeenmoon.py @@ -16,3 +16,36 @@ def longestConsecutive(self, nums: List[int]) -> int: answer = max(answer , length) return answer + + + +# 정렬하면 쉬운데 O(n)이 필요하네 → set으로 조회를 O(1)로 → 근데 중복으로 세네 → 시작점에서만 세자 + +# TC : O(n) +# SC : O(n) + +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + s = set() + + for num in nums: + s.add(num) + + ans = 0 + + for num in s: + if num - 1 in s: + continue + + sub_ans = 1 + next_num = num + 1 + while next_num in s: + sub_ans = sub_ans + 1 + next_num = next_num + 1 + ans = max(ans, sub_ans) + + return ans + + + + diff --git a/top-k-frequent-elements/sangbeenmoon.py b/top-k-frequent-elements/sangbeenmoon.py index f2ac82380d..7da37d2819 100644 --- a/top-k-frequent-elements/sangbeenmoon.py +++ b/top-k-frequent-elements/sangbeenmoon.py @@ -29,3 +29,30 @@ def topKFrequent(self, nums: List[int], k: int) -> List[int]: +# TC: O(nlogn) +# SC: O(n) + +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + count_map = {} + + for num in nums: + if num in count_map: + count_map[num] = count_map[num] + 1 + else: + count_map[num] = 1 + + tuple_list = [] + + for item in count_map.items(): + tuple_list.append(item) + + tuple_list.sort(key=lambda x: x[1], reverse=True) + + answer = [] + for i in range(k): + answer.append(tuple_list[i][0]) + + + return answer +