diff --git a/contains-duplicate/sangbeenmoon.py b/contains-duplicate/sangbeenmoon.py new file mode 100644 index 0000000000..00a7b03ca6 --- /dev/null +++ b/contains-duplicate/sangbeenmoon.py @@ -0,0 +1,11 @@ +# time : O(n) +# space : O(n) +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + d = {} + for num in nums: + if num in d: + return True + else: + d[num] = True + return False diff --git a/house-robber/sangbeenmoon.py b/house-robber/sangbeenmoon.py new file mode 100644 index 0000000000..6b734a01c8 --- /dev/null +++ b/house-robber/sangbeenmoon.py @@ -0,0 +1,16 @@ +# dp[i] = max(dp[i-2] + nums[i] , dp[i-1]) +# time : O(n) +# space : 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(dp[0], nums[1]) + for i in range(2, len(nums)): + dp[i] = max(dp[i-2] + nums[i] , dp[i-1]) + + return dp[len(nums) - 1] diff --git a/longest-consecutive-sequence/sangbeenmoon.py b/longest-consecutive-sequence/sangbeenmoon.py new file mode 100644 index 0000000000..fa310273d9 --- /dev/null +++ b/longest-consecutive-sequence/sangbeenmoon.py @@ -0,0 +1,18 @@ +# 30분 내로 풀지 못함. 풀이를 참고하였음. +# idea : x - 1 이 존재하지 않는 x 값에서만 loop 를 실행한다. +# time O(n) : 모든 숫자를 많아야 1,2번 방문. +# space O(n) +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + s = set(nums) + answer = 0 + for num in s: + if num - 1 not in s: + cur = num - 1 + length = 0 + while cur + 1 in s: + cur = cur + 1 + length = length + 1 + answer = max(answer , length) + + return answer diff --git a/top-k-frequent-elements/sangbeenmoon.py b/top-k-frequent-elements/sangbeenmoon.py new file mode 100644 index 0000000000..f2ac82380d --- /dev/null +++ b/top-k-frequent-elements/sangbeenmoon.py @@ -0,0 +1,31 @@ +# idea +# 1. 빈도수를 dict 에 저장한다. +# 2. 빈도수 내림차순으로 정렬한다. +# 3. 2에서 정렬한 entry 중 1번째, 2번째, ... k 번째 key 값을 모아서 List 로 반환한다. +# time : O(nlogn) +# space : O(n) +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + count_dict = {} + + for num in nums: + if num in count_dict: + count_dict[num] = count_dict[num] + 1 + else: + count_dict[num] = 1 + + tuple_list = [] + + for (count_key, count_value) in count_dict.items(): + tuple_list.append((count_key, count_value)) + + sorted_tuple_list = sorted(tuple_list, key=lambda x: x[1], reverse=True) + answer = [] + + for i in range(k): + answer.append(sorted_tuple_list[i][0]) + + return answer + + + diff --git a/two-sum/sangbeenmoon.py b/two-sum/sangbeenmoon.py new file mode 100644 index 0000000000..b3e9b294e9 --- /dev/null +++ b/two-sum/sangbeenmoon.py @@ -0,0 +1,9 @@ +# time : O(n^2) +# space : O(1) +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + for i in range(len(nums)): + for j in range(i + 1, len(nums)): + if nums[i] + nums[j] == target: + return [i,j] +