-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathleetcode0018.go
More file actions
45 lines (37 loc) · 764 Bytes
/
Copy pathleetcode0018.go
File metadata and controls
45 lines (37 loc) · 764 Bytes
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
/*
LeetCode 18: https://leetcode.com/problems/4sum/
*/
package leetcode
import (
"sort"
)
func fourSum(nums []int, target int) [][]int {
sort.Ints(nums)
result := make([][]int, 0)
for i := 0; i < len(nums)-3; {
for j := i + 1; j < len(nums)-2; {
k, m := j+1, len(nums)-1
for k < m {
sum := nums[i] + nums[j] + nums[k] + nums[m]
if sum < target {
k++
} else if sum > target {
m--
} else {
result = append(result, []int{nums[i], nums[j], nums[k], nums[m]})
k = increaseIndex18(nums, k)
}
}
j = increaseIndex18(nums, j)
}
i = increaseIndex18(nums, i)
}
return result
}
func increaseIndex18(nums []int, i int) int {
temp := i
for i < len(nums)-1 && nums[i] == nums[temp] {
i++
}
return i
}