diff --git a/contains-duplicate/hj4645.py b/contains-duplicate/hj4645.py new file mode 100644 index 000000000..f85e41b44 --- /dev/null +++ b/contains-duplicate/hj4645.py @@ -0,0 +1,11 @@ +class Solution: + # 리스트 안에 동일한 숫자가 2개 이상 존재하면 true를 반환해야 하는 문제 + # Set으로 변환 시 중복이 제거되므로 List와 Set의 크기를 비교해 답을 구할 수 있음 + def containsDuplicate(self, nums: List[int]) -> bool: + return len(nums) != len(set(nums)) + + # Time Complexity + # - set(nums) → O(n) + # - len(nums), len(set(nums)) → O(1) + # - Total: O(n) (n = number of list elements) + diff --git a/house-robber/hj4645.kt b/house-robber/hj4645.kt new file mode 100644 index 000000000..09c87cffa --- /dev/null +++ b/house-robber/hj4645.kt @@ -0,0 +1,19 @@ +class Solution { + // 배열에서 인접한 항은 접근할 수 없을 때, 인접하지 않은 항을 더해 가장 큰 값을 구하는 문제 + // 1. DP를 사용해 각 집마다 선택하거나 건너뛰는 경우를 누적 계산 + // 2. 현재 집을 털 때, 이전 집을 털지 않은 경우만 더할 수 있게끔 계산 + fun rob(nums: IntArray): Int { + if (nums.isEmpty()) return 0 + var prev1 = 0 // 바로 이전 집까지의 최대 이익 + var prev2 = 0 // 이전 이전 집까지의 최대 이익 + + for (num in nums) { + var temp = prev1 + prev1 = maxOf(prev2 + num, prev1) + prev2 = temp + } + + return prev1 + } +} + diff --git a/longest-consecutive-sequence/hj4645.kt b/longest-consecutive-sequence/hj4645.kt new file mode 100644 index 000000000..8cae84d36 --- /dev/null +++ b/longest-consecutive-sequence/hj4645.kt @@ -0,0 +1,26 @@ +class Solution { + // 배열에서 연속된 숫자의 개수를 구하는 문제 + // 1. 중복은 제거하고 카운트 + // 2. 정렬하지 않고 계산도 가능 + fun longestConsecutive(nums: IntArray): Int { + if(nums.isEmpty()) return 0 + + val numSet = nums.toHashSet() + var maxLen = 0 + + for(num in nums){ + if((num - 1) !in numSet){ + var currNum = num + var currLen = 1 + + while((currNum + 1) in numSet){ + currNum++ + currLen++ + } + if(currLen > maxLen) maxLen = currLen + } + } + return maxLen + } +} + diff --git a/top-k-frequent-elements/hj4645.py b/top-k-frequent-elements/hj4645.py new file mode 100644 index 000000000..780511712 --- /dev/null +++ b/top-k-frequent-elements/hj4645.py @@ -0,0 +1,12 @@ +class Solution: + # nums 에서 가장 빈도가 높은 k개의 요소를 찾는 문제 + # 딕셔너리와 정렬을 사용해 해결 + # 시간복잡도: O(n log n), 공간복잡도: O(n) + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + freq_map = {} + for num in nums: + freq_map[num] = freq_map.get(num, 0) + 1 + + sorted_nums = sorted(freq_map.items(), key=lambda x:x[1], reverse=True) + return [num for num, _ in sorted_nums[:k]] + diff --git a/two-sum/hj4645.py b/two-sum/hj4645.py new file mode 100644 index 000000000..5736bf1bf --- /dev/null +++ b/two-sum/hj4645.py @@ -0,0 +1,11 @@ +class Solution: + # 2개의 수를 합해 target이 되는 경우를 찾는 문제 + # 순서가 보장되는 python dictionary를 사용해서, + # 요소 x에 대해서 target-x 가 딕셔너리 내에 있는지를 찾는다. + def twoSum(self, nums: List[int], target: int) -> List[int]: + dict = {} + for i, num in enumerate(nums): + remain = target - num + if remain in dict: + return [dict[remain], i] + dict[num] = i