0016. 3Sum Closest - kumaeki/LeetCode GitHub Wiki

0016. 3Sum Closest


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 1:

Input: nums = [-1,2,1,-4], target = 1

Output: 2

Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Constraints:

  • 3 <= nums.length <= 10^3
  • -10^3 <= nums[i] <= 10^3
  • -10^4 <= target <= 10^4

解法1

排序, 遍历, 然后binarySearch

class Solution {
    public int threeSumClosest(int[] nums, int target) {

        Arrays.sort(nums);

        int result = 50000;
        int len = nums.length;

        for (int i = 0; i < len - 2; i++) {
            int numi = nums[i];
            for (int j = i + 1; j < len - 1; j++) {
                int k = target - numi - nums[j];
                int index = Arrays.binarySearch(nums, j + 1, len, k);
                if (index >= 0)
                    return target;

                index = -index - 1;
                if (index < len) {
                    int sum = numi + nums[j] + nums[index];
                    if (Math.abs(sum - target) < Math.abs(result - target))
                        result = sum;
                }

                if (index - 1 > j) {
                    int sum = numi + nums[j] + nums[index - 1];
                    if (Math.abs(sum - target) < Math.abs(result - target))
                        result = sum;
                }
            }
        }

        return result;
    }
}

解法2

Two points

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