leetcode第18题 四数之和 (双指针法+暴力搜索)

/*
方法一:使用回溯法暴力搜索
class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>>  ret=new ArrayList<List<Integer>>();
        List<Integer> list=new ArrayList<Integer>();
        subsetsWithDup(nums,ret,list,target,0);
        return ret;
        
    }
    public void subsetsWithDup(int[] ns,List<List<Integer>>  ret,List<Integer> list,int target,int start) {
        if(list.size()==4&&target==0){
             ret.add(new ArrayList(list));
            return;
        }
        if(list.size()==4) return;
        for(int i=start;i<ns.length;i++){
            if(i!=start&&ns[i]==ns[i-1]) continue;
            list.add(ns[i]);
            subsetsWithDup(ns,ret,list,target-ns[i],i+1);
            list.remove(list.size()-1);
        }
    }
}
*/

/*
方法二:双指针
*/
class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> ret = new ArrayList<>();
        Arrays.sort(nums);
        int n = nums.length;
        int start = 0;
        for (int i = start; i < n-3; i++){
            if (i > start && nums[i] == nums[i-1]){    // 确保i不重复
                continue;
            }
            for (int j = i+1; j < n-2; j++){
                if (j > (i+1) && nums[j] == nums[j-1]){    // 确保i不重复
                    continue;
                }
                int k = j+1;
                int l = n-1;
                while (k < l){
                    if (k > (j+1) && nums[k] == nums[k-1]){   // 确保k不重复
                        k++;
                        continue;
                    }
                    if (l < (n-1) && nums[l] == nums[l+1]){   // 确保l不重复
                        l--;
                        continue;
                    }
                    int s = nums[i] + nums[j] + nums[k] + nums[l];
                    if (s == target){
                        ret.add(Arrays.asList(nums[i], nums[j], nums[k], nums[l]));
                        k++;
                        l--;
                    } else if (s < target){
                        k++;
                    } else {
                        l--;
                    }
                }
            }
        }
        
        return ret;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值