forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0018-4Sum.go
45 lines (37 loc) · 776 Bytes
/
0018-4Sum.go
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
func fourSum(nums []int, target int) [][]int {
if len(nums) < 4 {
return [][]int{}
}
sort.Ints(nums)
result := make([][]int, 0)
for i, ival := range nums {
if i != 0 && nums[i] == nums[i - 1] {
continue
}
for j := i + 1; j < len(nums) - 1; j++ {
if j != i+1 && nums[j] == nums[j-1] {
continue
}
jval := nums[j]
for l, r := j+1, len(nums) - 1; l < r; {
lval, rval := nums[l], nums[r]
sum := ival + jval + lval + rval
switch {
case sum < target:
l++
case sum > target:
r--
default:
result = append(result, []int{ival, jval, lval, rval})
for ; l < r && nums[l] == nums[l+1]; l++ {
}
for ; l < r && nums[r] == nums[r-1]; r-- {
}
l++
r--
}
}
}
}
return result
}