diff --git a/contains-duplicate/acious.kt b/contains-duplicate/acious.kt new file mode 100644 index 0000000000..d2f96c9238 --- /dev/null +++ b/contains-duplicate/acious.kt @@ -0,0 +1,16 @@ +class Solution { + // 1 <= nums.length <= 10^5 + // Integer.MIN_VALUE(2,147,483,647) < -10^9 <= nums[i] <= 10^9 < Integer.MAX_VALUE(2,147,483,647) + // HashSet에 아이템을 하나씩 넣으면서 이미 존재하는 아이템이 있으면 true, 없으면 false + // 시간복잡도 : O(n), 공간복잡도 : O(n) + fun containsDuplicate(nums: IntArray): Boolean { + val set = HashSet() + for (num in nums) { + if (set.contains(num)) { + return true + } + set.add(num) + } + return false + } +} diff --git a/two-sum/acious.kt b/two-sum/acious.kt new file mode 100644 index 0000000000..cead1e7d96 --- /dev/null +++ b/two-sum/acious.kt @@ -0,0 +1,26 @@ +class Solution { + // nums의 모든 숫자를 Map에 저장. key는 nums의 숫자, value는 해당 숫자의 인덱스 + // target의 숫자가 동일한 숫자가 더해져야 하는 케이스 (예: target = 4, nums = [2, 2])를 위해 value는 List로 저장 + // 시간복잡도: O(n), 공간복잡도: O(n) + // improvement point : 한번의 루프를 순회하는 것으로도 문제를 해결할 수 있음. + fun twoSum(nums: IntArray, target: Int): IntArray { + val map = mutableMapOf>() + for (index in nums.indices) { // nums.indices는 nums의 인덱스 범위를 반환 + val list = map.getOrDefault(nums[index], mutableListOf()) + list.add(index) + map[nums[index]] = list + } + for (index in nums.indices) { + val complement = target - nums[index] + val complementIndices = map[complement] + if (complementIndices != null) { + for (complementIndex in complementIndices) { + if (complementIndex != index) { + return intArrayOf(index, complementIndex) + } + } + } + } + throw IllegalArgumentException("No two sum solution") + } +}