...
https://leetcode.com/problems/3sum/
Status | ||||
---|---|---|---|---|
|
Code Block | ||
---|---|---|
| ||
func threeSum(nums []int) (results [][]int) {
sort.Ints(nums)
k := 0
for k < len(nums) {
partResults := twoSum(nums[k+1:], -nums[k])
for _, r := range partResults {
results = append(results,
append([]int{nums[k]}, r...),
)
}
for v := nums[k]; k < len(nums) && nums[k] == v; k++ {}
}
return
}
func twoSum(nums []int, target int) (results [][]int) {
i, j := 0, len(nums)-1
for i < j {
sum := nums[i] + nums[j]
if sum == target {
results = append(results, []int{nums[i], nums[j]})
for v := nums[i]; i < len(nums) && nums[i] == v; i++ {}
for v := nums[j]; j >= 0 && nums[j] == v; j-- {}
} else if sum < target {
for v := nums[i]; i < len(nums) && nums[i] == v; i++ {}
} else {
for v := nums[j]; j >= 0 && nums[j] == v; j-- {}
}
}
return
} |
LC 18. 4Sum 四数之和
https://leetcode.com/problems/4sum/
...