[Leetcode] 3Sum Closest

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(itarget) {
                        hi--;
                        while(lo

你可能感兴趣的:([Leetcode] 3Sum Closest)