美文网首页
[Leetcode] 3Sum Closest

[Leetcode] 3Sum Closest

作者: lijia069 | 来源:发表于2017-12-20 17:20 被阅读0次

Related Topics:[Array][Two Pointers]
Similar Questions:[3Sum][[3Sum Smaller]

题目: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).

这道题让我们求最接近给定值的三数之和,是在之前3Sum问题的基础上又增加了些许难度,那么这道题让我们返回这个最接近于给定值的值,即我们要保证当前三数和跟给定值之间的差的绝对值最小。先将数组排个序,然后开始遍历数组,思路跟3Sum相似,都是先确定一个数,然后用两个指针lo和hi来滑动寻找另外两个数,每确定两个数,我们求出此三数之和,更新结果并移动指针。当和与target相等时,已找到最接近值,返回结果。

java解法:

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int i=0;
        int res=nums[0]+nums[1]+nums[nums.length-1];    
        while(i<nums.length-2) {
            //当与前一个元素相同时,跳过该元素的检查。
            if(i==0||(i!=0&&(nums[i]!=nums[i-1]))) {
                int lo=i+1;
                int hi=nums.length-1;
                while(lo<hi){
                    int sum=nums[i]+nums[lo]+nums[hi];
                    if(Math.abs(sum-target)<Math.abs(res-target)) {
                        res=sum;
                    };
                    //如果该元素与前(后)一元素相同,则跳过元素
                    if(sum<target) {
                        lo++;
                        while(lo<hi&&nums[lo]==nums[lo-1]) lo++;
                    }else if(sum>target) {
                        hi--;
                        while(lo<hi&&nums[hi]==nums[hi+1]) hi--;
                    }else {
                        return res;
                    }
                    
                }
            }
            i++;
        }
        return res;
    }
}

相关文章

网友评论

      本文标题:[Leetcode] 3Sum Closest

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