LeetCode 16. 3Sum Closest 最接近的三数之和(Java)

题目:

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

解答:

本题首先想到了与15题基本相同的思路,即先对数组进行排序后,采用双指针的解法
具体思路为:

  1. 采用 Arrays.sort() 对数组进行排序,用 res 记录目前三个数相加之和与 target 的差值,差值的绝对值越小,说明三个数总和越接近目标值
  2. 两个指针分别指向 i 的下一位和数组的尾部,计算当前三个数的差值 cur。比较当前差值 cur 和之前最小差值 res 的绝对值大小,若当前差值绝对值小,说明更接近 target,更新 res。
  3. 若差值 cur<0,说明三个数之和偏小,右移左指针;若 差值 cur>0,则说明三个数之和偏大,左移右指针
  4. 返回当前三个数最接近 target 之和,即 target-res
class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int res = Integer.MAX_VALUE;  
        for(int i=0; i<nums.length; i++) {
            int sum = target - nums[i];
            int left = i+1;
            int right = nums.length-1;                      
            while(left<right) {
                int cur = sum - nums[left] - nums[right];
                if(Math.abs(cur) < Math.abs(res)) {
                    res = cur;
                }
                if(cur > 0) {
                    left++;
                }else{
                    right--;
                }
            }
        }
        return target-res;
    }
}

你可能感兴趣的:(LeetCode)