[Leetcode] 4Sum

本文介绍了一种解决四数之和问题的高效算法。该算法通过先对数组进行排序,然后利用双指针技巧遍历数组寻找符合条件的四元组,确保了元素的非递减顺序且避免重复解。时间复杂度为O(n^3),适用于查找数组中是否存在四个数相加等于特定目标值的问题。

Given an array S of n integers, are there elements abc, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
  • The solution set must not contain duplicate quadruplets.

 

    For example, given array S = {1 0 -1 0 -2 2}, and target = 0.

    A solution set is:
    (-1,  0, 0, 1)
    (-2, -1, 1, 2)
    (-2,  0, 0, 2)

Solution:

O(n^3)的Time Efficiency.

 1 public class Solution {
 2     public List<List<Integer>> fourSum(int[] num, int target) {
 3         List<List<Integer>> result=new ArrayList<List<Integer>>();
 4         Arrays.sort(num);
 5         for(int i=0;i<num.length-3;++i){
 6             if(i>0&&num[i]==num[i-1])
 7                 continue;
 8             for(int j=i+1;j<num.length-2;++j){
 9                 if(j>i+1&&num[j]==num[j-1])
10                     continue;
11                 int low=j+1;
12                 int high=num.length-1;
13                 while(low<high){
14                     int sum=num[i]+num[j]+num[low]+num[high];
15                     if(sum==target){
16                         List<Integer> temp=new ArrayList<Integer>();
17                         temp.add(num[i]);
18                         temp.add(num[j]);
19                         temp.add(num[low]);
20                         temp.add(num[high]);
21                         result.add(temp);
22                         low++;
23                         high--;
24                         while(low<high&&num[low]==num[low-1])
25                             low++;
26                         while(low<high&&num[high]==num[high+1])
27                             high--;
28                     }
29                     else if(sum<target){
30                         low++;
31                     }
32                     else 
33                         high--;                        
34                 }
35             }
36         }
37         return result;
38     }
39 }

 

转载于:https://www.cnblogs.com/Phoebe815/p/4066298.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值