給定一個(gè)包含 n 個(gè)整數(shù)的數(shù)組 nums 和一個(gè)目標(biāo)值 target,判斷 nums 中是否存在四個(gè)元素 a,b,c 和 d ,使得 a + b + c + d 的值與 target 相等睦柴?找出所有滿足條件且不重復(fù)的四元組。
注意:
答案中不可以包含重復(fù)的四元組毡熏。
示例:
給定數(shù)組 nums = [1, 0, -1, 0, -2, 2]坦敌,和 target = 0。
滿足要求的四元組集合為:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
思路
最簡單直接的暴力痢法,不出意外地超時(shí)
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> L = new ArrayList<List<Integer>>();
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
for (int k = j + 1; k < nums.length; k++) {
for (int l = k + 1; l < nums.length; l++) {
List<Integer> list = new ArrayList<Integer>();
if (nums[i] + nums[j] + nums[k] + nums[l] == target) {
list.add(nums[i]);
list.add(nums[j]);
list.add(nums[k]);
list.add(nums[l]);
}
int f = 1;
for (int a = 0; a < L.size(); a++) {
if(L.get(a).equals(list)) {
f = 0;
}
}
if (f == 1) {
if (list.size() != 0) {
L.add(list);
}
}
}
}
}
}
return L;
}
}
思路
先遍歷兩個(gè)數(shù)狱窘,剩下的兩個(gè)數(shù)采用雙指針的方式掃描
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> L = new ArrayList<List<Integer>>();
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
int l = j + 1;
int r = nums.length - 1;
int temp = target - nums[i] - nums[j];
while (l < r) {
if (nums[l] + nums[r] == temp) {
List<Integer> list = new ArrayList<>();
list.add(nums[i]);
list.add(nums[j]);
list.add(nums[l]);
list.add(nums[r]);
int f = 1;
for (int a = 0; a < L.size(); a++) {
if(L.get(a).equals(list)) {
f = 0;
break;
}
}
if (f == 1) {
L.add(list);
}
r--;
l++;
}else if (nums[l] + nums[r] > temp) {
r--;
}else if (nums[l] + nums[r] < temp) {
l++;
}
}
}
}
return L;
}
}