File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ class Solution {
2+ // nums의 모든 숫자를 Map에 저장. key는 nums의 숫자, value는 해당 숫자의 인덱스
3+ // target의 숫자가 동일한 숫자가 더해져야 하는 케이스 (예: target = 4, nums = [2, 2])를 위해 value는 List로 저장
4+ // 시간복잡도: O(n), 공간복잡도: O(n)
5+ fun twoSum (nums : IntArray , target : Int ): IntArray {
6+ val map = mutableMapOf<Int , MutableList <Int >>()
7+ for (index in nums.indices) { // nums.indices는 nums의 인덱스 범위를 반환
8+ val list = map.getOrDefault(nums[index], mutableListOf ())
9+ list.add(index)
10+ map[nums[index]] = list
11+ }
12+ for (index in nums.indices) {
13+ val complement = target - nums[index]
14+ val complementIndices = map[complement]
15+ if (complementIndices != null ) {
16+ for (complementIndex in complementIndices) {
17+ if (complementIndex != index) {
18+ return intArrayOf(index, complementIndex)
19+ }
20+ }
21+ }
22+ }
23+ throw IllegalArgumentException (" No two sum solution" )
24+ }
25+ }
You can’t perform that action at this time.
0 commit comments