四数之和
题目:18. 四数之和
给你一个由 n
个整数组成的数组 nums
,和一个目标值 target
。请你找出并返回满足下述全部条件且不重复 的四元组 [nums[a], nums[b], nums[c], nums[d]]
(若两个四元组元素一一对应,则认为两个四元组重复):
0 <= a, b, c, d < n
a
、b
、c
和d
互不相同nums[a] + nums[b] + nums[c] + nums[d] == target
你可以按 任意顺序 返回答案 。
示例 1:
输入:nums = [1,0,-1,0,-2,2], target = 0
输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
示例 2:
输入:nums = [2,2,2,2,2], target = 8
输出:[[2,2,2,2]]
提示:
1 <= nums.length <= 200
-109 <= nums[i] <= 109
-109 <= target <= 109
方法一:
利用三数组求和思路破解。
go
func fourSum(nums []int, target int) [][]int {
Len := len(nums)
res := make([][]int, 0)
qSort18(nums, 0, Len-1)
for i := 0; i < Len; {
for j := i + 1; j < Len; {
l, r := j+1, Len-1
for l < r {
if nums[i]+nums[j]+nums[l]+nums[r] < target {
l++
for l < r && nums[l] == nums[l-1] {
l++
}
} else if nums[i]+nums[j]+nums[l]+nums[r] > target {
r--
for l < r && nums[r+1] == nums[r] {
r--
}
} else {
res = append(res, []int{nums[i], nums[j], nums[l], nums[r]})
l++
for l < r && nums[l] == nums[l-1] {
l++
}
r--
for l < r && nums[r+1] == nums[r] {
r--
}
}
}
j++
for j < Len && nums[j] == nums[j-1] {
j++
}
}
i++
for i < Len && nums[i] == nums[i-1] {
i++
}
}
return res
}
func qSort18(nums []int, low, high int) {
if low >= high {
return
}
pos := position18(nums, low, high)
qSort18(nums, low, pos-1)
qSort18(nums, pos+1, high)
}
func position18(nums []int, low, high int) int {
base := nums[low]
l, r := low, high
for l < r {
for l < r && nums[r] >= base {
r--
}
nums[l] = nums[r]
for l < r && nums[l] <= base {
l++
}
nums[r] = nums[l]
}
nums[l] = base
return l
}