Skip to content

Commit 47065bb

Browse files

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package leetcode.`3sum`
2+
3+
import org.junit.Test
4+
5+
class Solution {
6+
fun threeSum(nums: IntArray): List<List<Int>> {
7+
val resultList = arrayListOf<List<Int>>()
8+
if (nums.size < 3) return resultList
9+
nums.sort()
10+
for (i in 0 until nums.lastIndex - 1) {
11+
val target = 0 - nums[i]
12+
var p1 = i + 1
13+
var p2 = nums.lastIndex
14+
while (p1 < p2) {
15+
if ((nums[p1] + nums[p2]) == target) {
16+
val result = listOf(nums[p1], nums[i], nums[p2])
17+
if (!resultList.contains(result)) resultList.add(result)
18+
p1++
19+
} else if (target > (nums[p1] + nums[p2])) {
20+
p1++
21+
} else {
22+
p2--
23+
}
24+
}
25+
}
26+
return resultList
27+
}
28+
29+
30+
@Test
31+
fun test() {
32+
val test = intArrayOf(-1, 0, 1, 2, -1, -4)
33+
threeSum(test)
34+
}
35+
}

0 commit comments

Comments
 (0)