...
https://leetcode.com/problems/4sum/
Code Block |
---|
|
func fourSum(nums []int, target int) (results [][]int) {
sort.Ints(nums)
i := 0
for i < len(nums) - 3 {
j := len(nums) - 1
for i + 2 < j {
partResults := twoSum(nums[i+1:j], target-(nums[i]+nums[j]))
for _, r := range partResults {
results = append(results,
[]int{nums[i], r[0], r[1], nums[j]},
)
}
for v := nums[j]; j > i+2 && nums[j] == v; j-- {}
}
for v := nums[i]; i < len(nums)-3 && nums[i] == v; i++ {}
}
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
} |
直接利用 3Sum
Code Block |
---|
|
func fourSum(nums []int, target int) (results [][]int) {
sort.Ints(nums)
i := 0
for i < len(nums) - 3 {
partResults := threeSum(nums[i+1:], target-nums[i])
for _, r := range partResults {
results = append(results,
append([]int{nums[i]}, r...),
)
}
for v := nums[i]; i < len(nums)-3 && nums[i] == v; i++ {}
}
return
}
func threeSum(nums []int, target int) (results [][]int) {
sort.Ints(nums)
k := 0
for k < len(nums) {
partResults := twoSum(nums[k+1:], target-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
} |
nSum
Code Block |
---|
// nums should be already sorted
func nSum(nums []int, target int) (results [][]int) {
} |
双指针数组
LC 75. Sort Colors 颜色分类
...