-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.go
78 lines (73 loc) · 1.45 KB
/
Solution.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
70
71
72
73
74
75
76
77
78
import "strconv"
type Entry struct {
a1, a2, a3, a4 int
}
func(e *Entry) String() string {
return strconv.FormatInt(int64(e.a1), 10) +
"," + strconv.FormatInt(int64(e.a2), 10) +
"," + strconv.FormatInt(int64(e.a3), 10) +
"," + strconv.FormatInt(int64(e.a4), 10)
}
func fourSum(nums []int, target int) [][]int {
flag := make(map[string]bool)
sort(nums)
result := make([][]int, 0)
begin := 0
lenNums := len(nums) - 1
for begin + 2 < lenNums {
left := begin + 1
right := lenNums
lt := target - nums[begin]
for left + 1 < right {
i := left + 1
j := right
subTarget := lt - nums[left]
for i < j {
if nums[i] + nums[j] > subTarget {
j--
} else if nums[i] + nums[j] < subTarget {
i++
} else {
entry := &Entry{
a1:nums[begin],
a2:nums[left],
a3:nums[i],
a4:nums[j],
}
if !flag[entry.String()] {
r := []int{nums[begin], nums[left], nums[i], nums[j]}
result = append(result, r)
flag[entry.String()] = true
}
i++
j--
}
}
left++
}
begin++
}
return result
}
// quick sort
func sort(array []int) {
if len(array) == 0 {
return
}
left := 0
right := len(array) - 1
obj := array[left]
for left < right {
for left < right && array[right] >= obj {
right--
}
array[left] = array[right]
for left < right && array[left] <= obj {
left++
}
array[right] = array[left]
}
array[left] = obj
sort(array[:left])
sort(array[right+1:])
}