16. 3Sum Closest

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的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,353评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,482评论 0 23
  • 听到英雄两个字总是让人肃然起敬的,想到那些抛头颅洒热血的各路好汉。可我的英雄平平凡凡,不会驾着七彩祥云,也没有做过...
    三芙拉沃阅读 3,056评论 1 0
  • 文/微风不老 跟一个素昧平生的大姐聊天。聊着聊着,她突然很认真地看着我的眼睛说:“姑娘,看你幸福指数蛮高的,感觉整...
    山河九鼎阅读 1,748评论 2 1
  • 背景 起源是一款刀具LIQUIDIAMOND,号称可以达到HRc70+,目前市面较高端的刀具,一般的日本高端高碳钢...
    转丸阅读 4,819评论 0 0