您好,欢迎来到爱够旅游网。
搜索
您的当前位置:首页16. 最接近的三数之和

16. 最接近的三数之和

来源:爱够旅游网

代码:(暴力循环,可以过,但是花了18ms)

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        //尝试所有组合
        //与目标值相等则直接返回
        int closest = Integer.MAX_VALUE - Math.abs(target);
        for (int i = 0; i < nums.length - 2; i++) {
            for (int j = i + 1; j < nums.length - 1; j++) {
                for (int k = j + 1; k < nums.length; k++) {
                    int sum = nums[i] + nums[j] + nums[k];
                    if (sum - target == 0)
                        return sum;
                    if (Math.abs(closest - target) > Math.abs(sum - target))
                        closest = sum;
                }
            }
        }
        return closest;
    }
}

代码: (排序+双指针)

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        //排序
        Arrays.sort(nums);
        //遍历第一个数,第二个数和第三个数用双指针
        int closest = Integer.MAX_VALUE - Math.abs(target);
        for (int i = 0; i < nums.length - 2; i++) {
            int left = i + 1, right = nums.length - 1;
            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum == target)
                    return sum;
                else if (sum > target) {
                    right--;
                } else left++;
                //更新最接近值
                if (Math.abs(closest - target) > Math.abs(sum - target))
                    closest = sum;
            }
        }
        return closest;
    }
}

 

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- igbc.cn 版权所有 湘ICP备2023023988号-5

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务