四位数之和

四位数之和

暴力法,会超时。

两层循环,再使用双指针,觉得难点还是再去重复上。

class Solution {
    public List<List<Integer>> fourSum(int[] nums,int target) {
        Arrays.sort(nums);
        List<List<Integer>> res=new ArrayList<List<Integer>>();
        for(int i=0;i<nums.length-3;i++){
            if(i>0 && nums[i-1]==nums[i])
                continue;
            for(int j=i+1;j<nums.length-2;j++){
                if(j>i+1 && nums[j-1]==nums[j])
                    continue;
                int temp=target-nums[i]-nums[j];
                int first=j+1,end=nums.length-1;
                while(first<end){
                    while(nums[first]+nums[end]<temp && first<end)
                        first++;
                    while(nums[first]+nums[end]>temp && first<end)
                        end--;
                    if(first<end && nums[first]+nums[end]==temp){
                        List<Integer> tempres=new ArrayList<Integer>();
                        tempres.add(nums[i]);
                        tempres.add(nums[j]);
                        tempres.add(nums[first]);
                        tempres.add(nums[end]);
                        res.add(new ArrayList(tempres));
                        while(first<end){
                            if(nums[first]==nums[first+1])
                                first++;
                            else
                                break;
                        }
                        first++;
                        while(first<end){
                            if(nums[end-1]==nums[end])
                                end--;
                            else
                                break;
                        }
                        end--;
                    }
                }
            }
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/anhuibozhoushatu/article/details/84259368