16. 3Sum Closest

作者: 番茄晓蛋 | 来源:发表于2017-06-14 09:01 被阅读3次

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

** 解题思路 **
Similar to 3 Sum problem, use 3 pointers to point current element, next element and the last element.

If the sum is less than target, it means we have to add a larger element so next element move to the next. If the sum is greater, it means we have to add a smaller element so last element move to the second last element. Keep doing this until the end.

Each time compare the difference between sum and target, if it is less than minimum difference so far, then replace result with it, otherwise keep iterating.

    /* test cases:
    [1,1,1,0]  100  => 3
    [1,1,1,0] -100 => 2
    */
    public int threeSumClosest(int[] nums, int target) {
        int res = nums[0] + nums[1] + nums[nums.length - 1];
        Arrays.sort(nums);
        
        for (int i = 0; i < nums.length - 2; i++) {
            int start = i + 1, end = nums.length - 1;
            while (start < end) {
                int sum = nums[i] + nums[start] + nums[end];
                if (sum > target) {
                    end--;
                } else if (sum < target) {
                    start++;
                } else {
                    return sum;
                }
                if (Math.abs(sum -target) < Math.abs(res- target)){
                    res = sum;
                }
            }
        }
        return res;
    }

相关文章

  • LeetCode #16 2018-07-28

    16. 3Sum Closest Given an array nums of n integers and an...

  • Day3

    16. 3Sum Closest Given an array S of n integers, find thr...

  • LeetCode 16. 3Sum Closest

    16. 3Sum Closest Given an array S of n integers, find thr...

  • 16. 3Sum Closest

    题目: Given an array S of n integers, find three integers i...

  • 16. 3Sum Closest

    题目: 给定一个nums由n个整数和一个整数组成的数组target,找出三个整数nums,使总和最接近target...

  • 16. 3Sum Closest

    Given an array nums of n integers and an integer target, ...

  • 16. 3Sum Closest

    Description Given an array S of n integers, find three in...

  • 16. 3Sum Closest

    Given an array nums of n integers and an integer target, ...

  • 16. 3Sum Closest

    Description Given an array S of n integers, find three in...

  • 16. 3Sum Closest

    先排序,然后左右夹逼,每次当sum-target < diff 用diff记录下最小距离

网友评论

    本文标题:16. 3Sum Closest

    本文链接:https://www.haomeiwen.com/subject/wiajqxtx.html