题目:
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
注意:
答案中不可以包含重复的四元组。
示例:
给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。
满足要求的四元组集合为:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
java:
public static List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
//大于target直接返回.
if (nums[i] > 0 && nums[i] > target) {
return result;
}
//去重.
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
for (int j = i + 1; j < nums.length; j++) {
//对nums[j]去重.
if (j > j + 1 && nums[j] == nums[j - 1]) {
continue;
}
int left = j + 1;
int right = nums.length - 1;
while (left < right) {
long sum = (long) nums[i] + nums[j] + nums[left] + nums[right];
if (sum > target) {
right--;
} else if (sum < target) {
left++;
} else {
result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
//对left和right去重.
while (left < right && nums[left] == nums[left + 1]) left++;
while (left < right && nums[right] == nums[right - 1]) right--;
left++;
right--;
}
}
}
}
return result;
}
public static void main(String[] args) {
int nums[] = {1, 0, -1, 0, -2, 2};
int target = 0;
List<List<Integer>> result = fourSum(nums, target);
System.out.println(result);
}
}
Go:
func FourSum(nums []int, target int) [][]int {
//如果小于四个数返回.
if len(nums) < 4 {
return [][]int{}
}
//排序.
sort.Ints(nums)
var res [][]int
for i := 0; i < len(nums)-3; i++ {
num1 := nums[i]
//对nums[i]去重.
if i > 0 && nums[i] == nums[i-1] {
continue
}
for j := i + 1; j < len(nums)-2; j++ {
num2 := nums[j]
//对nums[j]去重.
if j > i+1 && nums[j] == nums[j-1] {
continue
}
l := j + 1
r := len(nums) - 1
for l < r {
num3 := nums[l]
num4 := nums[r]
sum := num1 + num2 + num3 + num4
if sum > target {
r--
} else if sum < target {
l++
} else {
res = append(res, []int{num1, num2, num3, num4})
for l < r && nums[l] == nums[l+1] {
l++
}
for l < r && nums[r] == nums[r-1] {
r--
}
l++
r--
}
}
}
}
return res
}
func main() {
nums := []int{1, 0, -1, 0, -2, 2}
target := 0
sum := LeetCode.FourSum(nums, target)
fmt.Println(sum)
}
方向和幻想一样重要.
如果大家喜欢我的分享的话.可以关注我的微信公众号
念何架构之路