码迷,mamicode.com
首页 > 其他好文 > 详细

4Sum

时间:2015-03-04 17:00:29      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:4sum   array   two points   

Given an array S of n integers, are there elements a, b, c, 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)
4sum与3sum一样 依次迭代枚举 代码如下:
public class Solution {
    public List<List<Integer>> fourSum(int[] num, int target) {
        List<List<Integer>> res=new ArrayList<>();
	        if(num.length<=3)return res;
	        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 sum=target-num[i]-num[j];
	                int left=j+1;
	                int right=num.length-1;
	                int flagl=0;
	                int flagr=0;
	                while(left<right){	                	
	                	if(num[left]+num[right]<sum){
	                	    flagl=1;
	                	}
	                	if(num[left]+num[right]>sum){
	                	    flagr=1;
	                	}
	                	if(num[left]+num[right]==sum){
	                		List<Integer> tmp=new ArrayList<Integer>();
	                		tmp.add(num[i]);
	                        tmp.add(num[j]);
	                        tmp.add(num[left]);
	                        tmp.add(num[right]);
	                        res.add(tmp);	
	                        flagl=1;
	                        flagr=1;
	                	}
	                	if(flagl==1){
	                	    left++;
	                	    while(left!=j+1&&left<=num.length-1&&num[left]==num[left-1]){
	                			    left++;
	                		}
	                		flagl=0;
	                	}
	                	if(flagr==1){
	                	    right--;
	                	    while(right>=j+1&&num[right]==num[right+1]){
		                			right--;
		                	}
		                	flagr=0;
	                	}
	                }
             }
	        }
	        return res;
    }
}

4Sum

标签:4sum   array   two points   

原文地址:http://blog.csdn.net/u012734829/article/details/44061319

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!