Skip to content

Commit 471cb9d

Browse files
committed
[Week3](gmlwls96) two-sum code.
1 parent f3cdc7b commit 471cb9d

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

two-sum/gmlwls96.kt

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,29 @@
11
class Solution {
2+
// 시간 : O(logN), 공간(2N)
23
fun twoSum(nums: IntArray, target: Int): IntArray {
4+
val sortNums = List(nums.size) { listOf(nums[it], it) }.sortedBy { it[0] }
5+
// 1. list( list('값', 'index')) 형태의 list를 만들고 값을 기준으로 정렬한다.
36

7+
var i = 0
8+
var j = sortNums.lastIndex
9+
// 2. 2포인터 방식으로 두 값을 합했을때 target이 되는 값을 찾는다.
10+
while (i < j) {
11+
val sum = sortNums[i][0] + sortNums[j][0]
12+
when {
13+
sum == target -> { // target과 sum이 일치할시 바로 return.
14+
return intArrayOf(
15+
min(sortNums[i][1], sortNums[j][1]),
16+
max(sortNums[i][1], sortNums[j][1])
17+
)
18+
}
19+
sum < target -> { // sum이 target보다 값이 작은경우 i를 한칸씩 더한다.
20+
i++
21+
}
22+
sum > target -> { // sum이 target보다 값이 큰경우 j를 한칸씩 내린다.
23+
j--
24+
}
25+
}
26+
}
27+
return intArrayOf()
428
}
529
}

0 commit comments

Comments
 (0)