Skip to content

Commit 8ae983c

Browse files
authored
Create 0018-4sum.kt
1 parent db55cd2 commit 8ae983c

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

kotlin/0018-4sum.kt

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
class Solution {
2+
fun fourSum(nums: IntArray, target: Int): List<List<Int>> {
3+
nums.sort()
4+
val res = ArrayList<ArrayList<Int>>()
5+
val temp = ArrayList<Int>()
6+
7+
fun kSum(k: Int, start: Int, targetSum: Long) {
8+
if (k != 2) {
9+
for (i in start..(nums.size - k)) {
10+
if (i > start && nums[i - 1] == nums[i])
11+
continue
12+
13+
temp.add(0, nums[i])
14+
kSum(k - 1, i + 1, targetSum - nums[i])
15+
temp.removeAt(0)
16+
}
17+
18+
return
19+
}
20+
21+
var left = start
22+
var right = nums.lastIndex
23+
while (left < right) {
24+
val sum = nums[left].toLong() + nums[right].toLong()
25+
if (sum < targetSum) {
26+
left++
27+
} else if (sum > targetSum) {
28+
right--
29+
} else {
30+
temp.add(0, nums[left])
31+
temp.add(0, nums[right])
32+
res.add(ArrayList(temp))
33+
temp.removeAt(0)
34+
temp.removeAt(0)
35+
36+
left++
37+
while (left < right && nums[left - 1] == nums[left])
38+
left++
39+
}
40+
}
41+
}
42+
43+
kSum(4, 0, target.toLong())
44+
return res
45+
}
46+
}

0 commit comments

Comments
 (0)