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).

这道题一开始我把是固定left和right,然后让i在中间循环,后来发现越来越混乱。之后看了答案,答案是先循环i, 然后用two pointers让left和right左右移动,就显得简单很多。

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int minDiff = Integer.MAX_VALUE;
        int closestSum = 0;
        for (int i = 0; i < nums.length; i++){
           int left = i + 1;
           int right = nums.length - 1;
           while (left < right){
               int sum = nums[i] + nums[left] + nums[right];
               int diff = Math.abs(target - sum);
               if (diff < minDiff){
                   minDiff = diff;
                   closestSum = sum;
               }
               if (sum < target){
                   left++;
               } else {
                   right--;
               }  
           } 
        } 
        return closestSum;
    }
}

你可能感兴趣的:(16. 3Sum Closest)