三数之和&&最接近的三数之和

//day08:三数之和。思路:先排序,然后遍历每一个数字的同时,再设置两个指针left/right
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        for(int i=0;i<nums.length-2;i++){
            if(i >=1 && nums[i] == nums[i-1])
                continue;
            int left = i+1;
            int right = nums.length -1;
            while(left < right){
                int sum = nums[i] + nums[left] + nums[right];
                if(sum == 0){
                    List<Integer> tmp = new ArrayList<>();
                    tmp.add(nums[i]);
                    tmp.add(nums[left]);
                    tmp.add(nums[right]);
                    res.add(tmp);
                    while(left+1 < right && nums[left] == nums[left+1])
                        left++;
                    while(right-1>left && nums[right] == nums[right-1])
                        right--;
                    left++;
                    right--;
                }
                else if(sum > 0)
                    right--;
                else
                    left++;
            }
        }
        return res;
    }
/**
    day08:最接近的三数之和(时间效率太低)
    思路:dfs
    */
    public int threeSumClosest(int[] nums, int target) {
        int[] res = {Integer.MAX_VALUE};
        helper(res, nums, target, 0, 0, 0);
        return res[0];
    }
    
    public static void helper(int[] res, int[] nums,int target, int pos, int sum, int count){
        if(count == 3){
            //特殊情况
            if(res[0] == Integer.MAX_VALUE && target <= 0){
                res[0] = sum;
                return;
            }
            if(Math.abs(sum - target) < Math.abs(res[0] - target))
                res[0] = sum;
            return;
        }
        for(int i=pos;i<nums.length;i++){
            helper(res, nums,target, i+1, sum+nums[i], count+1);
        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值