Leetcode-018-四数之和

Leecode-18. 四数之和

思路:排序+双指针

给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 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]
]

方法:排序+双指针

算法思路(同leetcode015 所以这里不再阐述 有15题基础看代码就秒懂了)

  • 首先对排序后的数组进行遍历,固定一个nums[i] 。
  • 其次使用一个指针L指向 i + 1 的位置,一个指针R指向 nums.length - 1的位置,同时计算nums[i] + nums[L] + nums[R],计算这三个数的和是否等于0
  • 细节条件一定要注意
    • 如果nums[i] > 0 ,那么这三个数的和比不可能等于0
    • 如果nums[i] == nums[i -1] ,则说明该数字重复,会导致结果的重复,所以应该跳过
    • 当sum == 0的时候,如果nums[L] == nums[L+1],则会导致结果的重复,应该跳过,(L++)
    • 当sum == 0的时候,如果nums[R] == nums[R - 1],则会导致结果的重复,应该跳过,(R–)

举个例子:

  1. 首先进行排序

mark

  1. 第一轮循环

mark

mark

mark

mark

mark

mark

  1. 第二轮循环

mark

mark

mark

  1. 第三轮循环

mark

mark

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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class Solution {
public static List<List<Integer>> fourSum(int[] nums, int target) {
// 结果集
List<List<Integer>> res = new ArrayList<>();

// 特判
if(nums == null || nums.length < 4){
return res;
}
int len = nums.length;

// 1.对数组进行排序
Arrays.sort(nums);

// 2. 双指针遍历
for(int i = 0;i < len - 3;i++){
// 剪枝操作
if(i > 0 && nums[i] == nums[i - 1]){
continue;
}

if(nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target){
break;
}

if (nums[i] + nums[len - 3] + nums[len - 2] + nums[len - 1] < target) {
continue;
}

for(int j = i + 1; j < len - 2;j++){
// 剪枝操作
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
if (nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) {
break;
}
if (nums[i] + nums[j] + nums[len - 2] + nums[len - 1] < target) {
continue;
}

// 双指针操作
int left = j + 1;
int right = len - 1;

while(left < right){
int sum = nums[i] + nums[j] + nums[left] + nums[right];

// 找到对应的结果
if(sum == target){
res.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));

// 去重操作
while(left < right && nums[left] == nums[left + 1]){
left++;
}
left++;

// 去重操作
while(left < right && nums[right] == nums[right - 1]){
right--;
}
}else if(sum < target){
// 和小于target
left++;
}else{
// 和大于target
right--;
}
}
}
}
return res;
}

public static void main(String[] args) {
int[] arr = new int[]{1, 0, -1, 0, -2, 2};
System.out.println(fourSum(arr,0));
}
}

复杂度分析:

  • 时间复杂度:O(n^3) 排序O(nlogn) + 循环O(n^3) = O(n^3)

  • 空间复杂度:O(n),其中 n 是数组的长度。空间复杂度主要取决于排序额外使用的空间。此外排序修改了输入数组 nums,实际情况中不一定允许,因此也可以看成使用了一个额外的数组存储了数组nums 的副本并排序,空间复杂度为 O(n)。

打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2019-2022 Zhuuu
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信