[LeetCode] 16. 3Sum Closest Java

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

分析:这道题目给了我们一个nums array 和一个 target, 让我们找到一组三数之和,并且是最接近于target的。由于我们做过了三数之和,所以差不多是一样方法来做这道题(这里充分说明了,要老老实实顺着题号做下去,较先的题目都可以被用来辅助之后的题)。方法就是先sort一下array,为啥要sort呢,因为要用到two pointers 来遍历找两数之和,只有在从小到大排序之后的结果上,才能根据情况移动left 和right。 当确定好了第一个数字后,就在剩下的array里找两数之和,在加上第一个数字,用这个temp_sum减去target 来得到temp_diff,如果temp_diff比之前的小,那么更新diff 和 closestSum。 利用two pointers 特性, 如果temp_sum 比target 小的话,说明我们需要更大的sum,所以要让left++以便得到更大的sum。 如果temp_sum 比target 大的话,我们就需要更小的sum。如果相等的话,直接return 就可以了。因为都相等了,那么差值就等于0,不会有差值再小的了。

class Solution {
    public int threeSumClosest(int[] nums, int target) {
    
        int closeTarget = nums[0] + nums[1] + nums[2];
        Arrays.sort(nums);
        int minReduce = Math.abs(closeTarget - target);

        for(int i=0;i<nums.length-2;i++){
            int left = i+1,right = nums.length-1;
            while(left < right){
                int total = nums[left]+nums[right]+ nums[i];
                if(total==target)
                    return target;
                else if(total<target){
                    left++;
                }else
                    right--;
                
                if(minReduce > Math.abs(total-target)){
                    minReduce = Math.abs(total - target);
                    closeTarget = total;
                }
            }
        }
        
        
        return closeTarget;
    }
}
原文地址:https://www.cnblogs.com/271934Liao/p/8478225.html