-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFourSum.kt
More file actions
31 lines (29 loc) · 942 Bytes
/
FourSum.kt
File metadata and controls
31 lines (29 loc) · 942 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package leetcode
/**
* Problem description on [LeetCode](https://leetcode.com/problems/4sum/)
*/
class FourSum {
fun fourSum(nums: IntArray, target: Int): List<List<Int>> {
val res = mutableSetOf<List<Int>>()
nums.sort()
for (a in 0 until nums.size - 3) {
for (b in a + 1 until nums.size - 2) {
var c = b + 1
var d = nums.lastIndex
while (c < d) {
val sum = nums[a].toDouble() + nums[b] + nums[c] + nums[d]
if (sum.toLong() == target.toLong()) {
res.add(listOf(nums[a], nums[b], nums[c], nums[d]))
c++
d--
} else if (sum < target) {
c++
} else {
d--
}
}
}
}
return res.toList()
}
}