Leetcode 16. Closest 3 Sum

题目名称:16. Closest 3 Sum

难度:Medium

知识点:双指针

解题思路:这道题特点是只需返回最靠近的三个数字的和,因此我们可以对数组进行排序,排序之后遍历整个数组,其中的每个数字作为第一个数字,求其与目标和的差值,在剩余的数字中寻找最靠近的差值,因为数组已经排序,因此可以用双指针,计算每一组三个数字与目标值的距离,如果绝对值比较小,我们就存起来这个值。另外,如果第一个数字的三倍已经比目标和大或者相等了,那我们只要看当前数字和其后面两个数字就好,不需要双指针去寻找了,再有就是我们在调整双指针的时候,如果挪动后比之前的差距还要大了,那我们可以跳出当前双指针的寻找,即在本轮中,我们已经找到了最靠近的组合。

Java代码如下:

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        int result = nums[0] + nums[1] + nums[2];
        Arrays.sort(nums);
        int temp_sum = 0;
        int sum_pre = 0;
        for(int i = 0; i< nums.length-2; i++){
            int distance = target-nums[i];
            int front = nums.length-1;
            int back = i+1;
            if(nums[i] * 3 > target){
                temp_sum = nums[i] + nums[i+1] + nums[i+2];
                if(Math.abs(target - temp_sum) < Math.abs(result - target)){
                    result = temp_sum;
                } 
                continue;
            }
            while(back < front){
                temp_sum = nums[front]+nums[back]+nums[i];
                sum_pre = temp_sum;
                if(Math.abs(target - sum_pre) > Math.abs(target - temp_sum)){
                    break;
                }
                if( temp_sum < target){
                    back ++;
                }else{
                    front --;
                }
                if(Math.abs(target - temp_sum) < Math.abs(result - target)){
                    result = temp_sum;
                } 
            }
        }
        return result;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值