-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4sum.go
69 lines (58 loc) · 1.3 KB
/
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package main
import (
"fmt"
"sort"
)
// source: https://leetcode.com/problems/4sum/
func threeSum(nums []int, prev, target int) [][]int {
if len(nums) < 3 {
return [][]int{}
}
length := len(nums)
res := make([][]int, 0, length/2)
for i := 0; i < length; i++ {
if i != 0 && nums[i-1] == nums[i] {
continue
}
for l, r := i+1, length-1; l < r; {
n := nums[i] + nums[l] + nums[r]
if n == target {
res = append(res, []int{nums[i], nums[l], nums[r]})
for dup := nums[l]; l < r && nums[l] == dup; {
l++
}
} else if n > target {
r--
} else {
l++
}
}
}
return res
}
func fourSum(nums []int, target int) [][]int {
var threes [][]int
res := make([][]int, 0)
sort.Ints(nums)
for i := 0; i < len(nums)-3; i++ {
if i != 0 && nums[i-1] == nums[i] {
continue
}
threes = threeSum(nums[i+1:], nums[i], target-nums[i])
for _, t := range threes {
temp := append([]int{nums[i]}, t...)
res = append(res, temp)
}
}
return res
}
func main() {
// Example 1
var nums1 = []int{1, 0, -1, 0, -2, 2}
var target1 int = 0
fmt.Println("Expected: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] Output: ", fourSum(nums1, target1))
// Example 2
var nums2 = []int{2, 2, 2, 2, 2}
var target2 int = 8
fmt.Println("Expected: [[2,2,2,2]] Output: ", fourSum(nums2, target2))
}