File tree 1 file changed +47
-0
lines changed
1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ fun fourSum (nums : IntArray , target : Int ): List <List <Int >> {
3
+ val target = target.toLong()
4
+
5
+ nums.sort()
6
+
7
+ val result = mutableListOf<List <Int >>()
8
+
9
+ var prevA: Int? = null
10
+ var prevB: Int? = null
11
+ var prevC: Int? = null
12
+
13
+ for (a in nums.indices) {
14
+ if (nums[a] == prevA) {
15
+ continue
16
+ }
17
+
18
+ for (b in (a + 1 ).. nums.lastIndex) {
19
+ if (nums[a] == prevA && nums[b] == prevB) {
20
+ continue
21
+ }
22
+
23
+ for (c in (b + 1 ).. nums.lastIndex) {
24
+ if (nums[a] == prevA && nums[b] == prevB && nums[c] == prevC) {
25
+ continue
26
+ }
27
+
28
+ val sum3 = nums[a].toLong() + nums[b] + nums[c]
29
+ for (d in (c + 1 ).. nums.lastIndex) {
30
+ val sum4 = sum3 + nums[d]
31
+ if (sum4 > target) {
32
+ break
33
+ } else if (sum4 == target) {
34
+ result + = listOf (nums[a], nums[b], nums[c], nums[d])
35
+ prevA = nums[a]
36
+ prevB = nums[b]
37
+ prevC = nums[c]
38
+ break
39
+ }
40
+ }
41
+ }
42
+ }
43
+ }
44
+
45
+ return result
46
+ }
47
+ }
You can’t perform that action at this time.
0 commit comments