16. 最接近的三数之和

链接:https://leetcode.cn/problems/3sum-closest/
题目:给你一个长度为 n 的整数数组 nums 和 一个目标值 target。从 nums 中选出三个整数,使它们的和与 target 最接近。返回这三个数的和。且题目确认唯一解。
思路:因为数组长度范围是1000,如果用暴力法n^3会超时,降低时间复杂度,对数组排序,遍历数组期间头尾指针查找三数和tempSum与target的差值,比较过程中有三种情况:
tempSum==target —>直接跳出程序,
tempSum<target —>左指针右移
tempSum>target —>右指针左

代码:

public static int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int distance = Integer.MAX_VALUE;
        int result = Integer.MIN_VALUE;
        for (int i=1;i<nums.length-1;i++){
            int mid = nums[i];
            int left = 0;
            int right = nums.length-1;
//            使用头尾指针向中间遍历
            inner:while (left<right){
//                下标重合
                if (left==i||right==i){
                    break inner;
                }
                int tempSum = mid+nums[left]+nums[right];
                if (Math.abs(tempSum-target)<distance){
                    distance=Math.abs(tempSum-target);
                    result=tempSum;
                }
                if (tempSum<target){
                    left++;
                }else if (tempSum==target){
                    return tempSum;
                }else {
                    right--;
                }
            }
        }
        return result;
    }

作者小白,侵权请私信删
2022.11.07

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值