-
Notifications
You must be signed in to change notification settings - Fork 0
/
18.四数之和.go
49 lines (45 loc) · 929 Bytes
/
18.四数之和.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
/*
* @lc app=leetcode.cn id=18 lang=golang
*
* [18] 四数之和
*/
// @lc code=start
func fourSum(nums []int, target int) [][]int {
sort.Ints(nums)
var res [][]int
var m = make(map[string]bool)
l := len(nums)
if l < 4 {
return res
}
for i := 0; i < l-3; i++ {
if nums[i]+nums[i+1]+nums[i+2]+nums[i+3] > target {
break
}
for j := i + 1; j < l-2; j++ {
if nums[i]+nums[j]+nums[j+1]+nums[j+2] > target {
break
}
left, right := j+1, l-1
for left < right {
sum := nums[i] + nums[j] + nums[left] + nums[right]
if sum == target {
key := fmt.Sprintf("%d#%d#%d#%d", nums[i], nums[j], nums[left], nums[right])
if _, ok := m[key]; !ok {
m[key] = true
res = append(res, []int{nums[i], nums[j], nums[left], nums[right]})
}
left++
}
if sum > target {
right--
}
if sum < target {
left++
}
}
}
}
return res
}
// @lc code=end