LeetCode-四数之和

题目

出处:LeetCode 算法第18题

给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,**b,cd ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。

注意:

答案中不可以包含重复的四元组。

示例:

1
2
3
4
5
6
7
8
给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。

满足要求的四元组集合为:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]

思路

  • 首先对数组进行排序,设置两个for循环,作为四个数中的前两个数,有可能有两个相同的数,遇到相同的数跳过,这样做是为了避免重复
  • 四个数中的后两个数怎么办,通过设置两个指针m和n,m从数组前往后进行遍历,n用来从数组后往前进行遍历。m>=n是结束循环的条件
  • 遇到 target == a + b + c + d 的数就加到ArrayList中

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
public class Basic18 {
public static List<List<Integer>> forSun(int[] num, int target) {
List<List<Integer>> list = new ArrayList();
//将数组进行排序
Arrays.sort(num);
//第一个加数
for (int i = 0; i < num.length - 3; i++) {
//判断第一个加数使用是否重复
if (i != 0 && num[i] == num[i - 1]) {
continue;
}

//第二个加数
for (int j = i + 1; j < num.length - 2; j++) {
//判断第二个加数使用是否重复
if (j != i + 1 && num[j] == num[j - 1]) {
continue;
}
//第三个数
int left = j + 1;
//第四个数
int right = num.length - 1;
while (left < right) {
int sum = num[i] + num[j] + num[left] + num[right];
if (sum < target) {
left++;
} else if (sum > target) {
right--;
} else {
List<Integer> temp = new ArrayList<>();
temp.add(num[i]);
temp.add(num[j]);
temp.add(num[left]);
temp.add(num[right]);
list.add(temp);
left++;
right--;
//保证再次使用第三个数不重复
while (left < right && num[left] == num[left - 1]) {
left++;
}
//保证再次使用第四个数不重复
while (left < right && num[right] == num[right + 1]) {
right--;
}
}
}
}
}

return list;
}

@Test
public void test1() {
int[] num = new int[]{1, 0, -1, 0, -2, 2};
int target = 0;
List list = forSun(num, target);
for (Iterator it = list.iterator(); it.hasNext(); ) {
System.out.println(it.next());
}
}
}