16、最接近的三数之和

问题描述

在这里插入图片描述

问题分析

分析题目,和上一个题目相似。我就简述一下思路:将数组排好序,固定第一个数,在另外两个指针的对撞过程中,如果三数之和距离target更近了,则更新;移动第一个数,重复上述过程。


解法:对撞指针

  • 时间复杂度:O( n2 ),其中n表示数组的长度。

Java代码

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        List<Integer> results = new ArrayList<>();
        int instence = Integer.MAX_VALUE;
        int result = 0;

        Arrays.sort(nums);
        for (int first = 0; (nums.length >= 3) && (first < nums.length-2); first++) {
            //与前一个first所对的数字不重复
            if (!(first > 0 && nums[first] == nums[first-1])){
                int i = first + 1;
                int j = nums.length - 1;
                int now_result;
                int now_instence;
                while (i < j){//Math.abs(nums[i] + nums[j] + nums[first] - target) < Math.abs(instence)
                    now_result = nums[i] + nums[j] + nums[first];
                    now_instence = target - now_result;

                    if (Math.abs(now_instence) < Math.abs(instence)){
                        instence = now_instence;
                        result = now_result;
                    }

                    if (now_instence == 0){
                        return result;
                    } else if (now_instence < 0){
                        //在target的右边,得变小
                        do {
                            j--;
                        }while (j < nums.length-1 && i < j && nums[j] ==  nums[j+1]);
                    } else {
                        //在target的左边,得变大
                        do {
                            i++;
                        }while (i > 0 && i < j && nums[i] == nums[i-1]);
                    }

                }
            }

        }
        return result;
    }
}

结果分析

以上代码的执行结果:

执行时间内存消耗
19ms35.7MB

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值