File tree Expand file tree Collapse file tree 1 file changed +24
-0
lines changed Expand file tree Collapse file tree 1 file changed +24
-0
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
+ // 시간 : O(logN), 공간(2N)
2
3
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를 만들고 값을 기준으로 정렬한다.
3
6
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()
4
28
}
5
29
}
You can’t perform that action at this time.
0 commit comments