Given an array nums
of n integers and an integer target
, are there elements a, b, c, and d in nums
such that a + b + c + d = target
? Find all unique quadruplets in the array which gives the sum of target
.
Note:
The solution set must not contain duplicate quadruplets.
Example:
Given array nums = [1, 0, -1, 0, -2, 2], and target = 0. A solution set is: [ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2] ]
package main
import(
"sort"
"fmt"
)
func fourSum(nums []int, target int) [][]int {
var result [][]int
if(len(nums) < 4){
return result
}
sort.Ints(nums)
for i := 0; i < len(nums); i++ {
if i > 0 && nums[i] == nums[i-1] {
continue
}
for j := i + 1; j < len(nums); j++ {
if j > i+1 && nums[j] == nums[j-1] {
continue
}
k := j + 1
l := len(nums) - 1
for k < l {
sum := nums[i] + nums[j] + nums[k] + nums[l]
if sum == target {
result = append(result, []int{nums[i], nums[j], nums[k], nums[l]})
k++
for ; k < l && nums[k] == nums[k-1]; k++ {
}
} else if sum < target {
k++
} else {
l--
}
}
}
}
return result
}
func main(){
nums := []int{1, 0, -1, 0, -2, 2}
result := fourSum(nums, 0)
fmt.Println(result)
}
采取遍历的方式:
1、首先判断数组中数据数量,少于4个直接返回
2、对数组中的元素进行排序
3、第一层循环i,遍历数组中的每一个元素,重复的相同元素直接跳过,第二层循环从i+1开始遍历数组中的每一个元素,重复元素跳过,第三层从j+1开始,同时和第四个数一起遍历,第四个数从数组的末尾开始向前遍历,终止条件是第三个数的索引小于第四个数,并将四个数相加,与target的大小进行比较,相等则加入到result中,小于target第三个数的索引向后,大于target则第四个数的索引向前移动。