云小杰

相对于绝对成功的汲汲渴求,越无杂质的奔赴,越是动人。

要一个黄昏, 满是风, 和正在落下的夕阳。如此, 足够我爱这破碎泥泞的人间。


Download the theme

最接近的三数之和

16. 最接近的三数之和

题目描述

给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

示例:

输入nums = [-1,2,1,-4], target = 1
输出2
解释 target 最接近的和是 2 (-1 + 2 + 1 = 2) 

方法:排序+双指针

本题与三数之和类似,都可以使用排序+双指针的方式来实现。

  • 其实最简单可以使用三层循环暴力求解,但是这样时间复杂度比较高。
  • 排序+双指针
    • 将数组排序,然后每次考虑第一个元素 a 以后,对于剩下的元素 bc,我们希望它们的值接近于 target-a
    • 我们可以将 ba 所在元素的下一个开始,c 从最后一个元素开始,同时遍历。
      • a+b+c=target,则直接返回。
      • a+b+c!=target,则判断与 target 之间插值绝对值的大小。同时判断与 target 的大小关系:
        • a+b+c<target,则 c 所在的指针向前移动。
        • a+b+c>target,则 b 所在的指针向后移动。
class Solution {
    public int threeSumClosest(int[] nums, int target) {
        int best = 10000000;
        Arrays.sort(nums);
        int length = nums.length;
        for (int first=0;first<length;++first){
            if (first>0 && nums[first]==nums[first-1]){
                continue;
            }
            int second = first + 1, third = length - 1;
            while (second < third){
                int curr = nums[first] + nums[second] + nums[third];
                if (curr == target){
                    return curr;
                }
                if (Math.abs(curr-target) < Math.abs(best-target)){
                    best = curr;
                }
                if (curr < target){
                    int j = second + 1;
                    while (j<third && nums[j]==nums[second]){
                        ++j;
                    }
                    second = j;
                } else {
                    int k = third - 1;
                    while (k>second && nums[k]==nums[third]){
                        --k;
                    }
                    third = k;
                }
            }
        }
        return best;
    }
}

若定义 int best = Integer.MAX_VALUE 则无法通过,有一个用例一直会报错。数组是 -3,-2,-5,3,-4, target 为 -1。是因为 best减去复数超出了 Integer 的范围了吗?

最近的文章

移除元素

27. 移除元素题目描述给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组。元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。示例1:输入:nums = [3,2,2,3], val = 3输出:2, nums = [2,2]解释:函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。你不需要考虑数组中超出新长度后面的元素。...…

继续阅读
更早的文章

三数之和

三数之和题目描述给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。注意:答案中不可以包含重复的三元组。方法:排序+双指针class Solution { public List<List<Integer>> threeSum(int[] nums) { int n = nums.length; Arrays.sort...…

继续阅读