Leetcode 16 3Sum Closest

在这里插入图片描述
思路: two pointer。其实这题就是第15题的变形(three sum)。具体来说就是先fix第一个数字(遍历),然后这时不是要找剩下的两个数字吗,这两个数字就用two pointer的方法来找。唯一的区别就是,这题可能会找不到三个数加起来等于target的,所以我们需要追踪三个数之合与target的差,存储最小的差。其他的实现和15题一模一样。话不多说,直接上代码:

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int res = 0;
        int distance = Math.abs(nums[0] + nums[1] + nums[2] - target);
        for(int i = 0; i < nums.length - 2; i++){
            int left = i + 1, right = nums.length - 1, remain = target - nums[i];
            while(left < right){
                if(Math.abs(remain - nums[left] - nums[right]) <= distance){
                    distance = Math.abs(remain - nums[left] - nums[right]);
                    res = nums[i] + nums[left] + nums[right];
                } 
                
                if(nums[left] + nums[right] == remain){
                    return nums[i] + nums[left] + nums[right];
                }else if(nums[left] + nums[right] > remain){ 
                    right--;
                }else{
                    left++;
                }  
            }
        }
        return res;
    }
}

总结:

  1. 求int绝对值: Math.abs(int n);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值