和3sum类似,要求四个数值和等于target。。。。。。。。。先对数组排序,利用二重循环先遍历两个数....之后利用头尾指针根据sum和target的大小关系移动头或尾指针确定合适答案.......要注意的是由于num中会存在重复元素...为了避免答案集合重复,每次选择数的时候都要判断一下以避免和之前考虑过的相同的数出现重复....
public class Solution {
public List<List<Integer>> fourSum(int[] num, int target) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
Arrays.sort(num);
int len = num.length;
for(int i=0;i<len-1;i++)
{
if( i>0&&num[i]==num[i-1] )
{
continue;
}
for( int j=i+1;j<len-1;j++ )
{
if(j>i+1&&num[j]==num[j-1])
{
continue;
}
int st = j+1;
int ed = len-1;
while(st<ed)
{
if(st>j+1&&num[st]==num[st-1])
{
st++;
continue;
}
if(ed<len-1&&num[ed]==num[ed+1])
{
ed--;
continue;
}
int sum = num[i]+num[j]+num[st]+num[ed];
if( sum == target )
{
List<Integer> temp = new ArrayList<Integer>();
temp.add(num[i]);
temp.add(num[j]);
temp.add(num[st]);
temp.add(num[ed]);
res.add(temp);
st++;
}
else if(sum<target)
{
st++;
}
else
{
ed--;
}
}
}
}
return res;
}
}