标签: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:
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 array two points
原文地址:http://blog.csdn.net/u012734829/article/details/44061319