LeetCode(18) - 4Sum

本文详细介绍了一种解决四数之和问题的高效算法,通过借鉴三数之和的思路,将复杂度从O(n^4)降低到O(n^3)。通过对数组进行排序并运用双指针技巧,避免了重复计算,最终实现了问题的有效解决。

  思路和3Sum一样,只是把O(n^4)变成了O(n^3),思路详细见3sum。最终能够ac。

  代码如下:

 1 public class Solution {
 2     public List<List<Integer>> fourSum(int[] nums, int target) {
 3         List<List<Integer>> res = new ArrayList<List<Integer>>();
 4         //先排序
 5         Arrays.sort(nums);
 6         for (int i = 0; i < nums.length - 3; i++) {
 7             //判断重复
 8             if (i != 0 && nums[i] == nums[i - 1]) continue;
 9             for (int j = i + 1; j < nums.length - 2; j++) {
10                 //判断重复
11                 if (j != i + 1 && nums[j] == nums[j - 1]) continue;
12                 int head = j + 1;
13                 int tail = nums.length - 1;
14                 while (head < tail) {
15                     //判断重复
16                     if (head != j+1 && nums[head] == nums[head - 1]) {
17                         head++;
18                         continue;
19                     }
20                     int sum = nums[i] + nums[j] + nums[head] + nums[tail];
21                     if (sum > target) tail--;
22                     else if (sum < target) head++;
23                     else {
24                         List<Integer> list = new ArrayList<Integer>();
25                         list.add(nums[i]);
26                         list.add(nums[j]);
27                         list.add(nums[head++]);
28                         list.add(nums[tail--]);
29                         res.add(list);
30                     }
31                 }
32             }
33         }
34         return res;
35     }
36 }

 

转载于:https://www.cnblogs.com/kepuCS/p/5271682.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值