533.Two Sum - Closest to target

描述

找到两个数字使得他们和最接近target,返回最接近值

样例

nums =[-1, 2, 1, -4],target =4.最接近值为1

挑战

Do it in O(nlogn) time complexity.

注意

1. two sum的题用两根指针来解一般都要先排序
2. 应在当nums[left]和nums[right]计算完成后书写left++和right--

代码

  1. version1
public class Solution {
    /*
     * @param nums: an integer array
     * @param target: An integer
     * @return: the difference between the sum and the target
     */
    public int twoSumClosest(int[] nums, int target) {
        if (nums == null && nums.length < 2) {
            return -1;
        }

        Arrays.sort(nums);
        int left = 0, right = nums.length - 1;
        int differ = Integer.MAX_VALUE;
        while (left < right) {
            if (nums[left] + nums[right] < target) {
                differ = Math.min(differ, target - nums[left] - nums[right]);
                left++;
            } else {
                differ = Math.min(differ, nums[left] + nums[right] - target);
                right--;
            }
        }
        return differ;
    }
}
  1. version2
public class Solution {
    /*
     * @param nums: an integer array
     * @param target: An integer
     * @return: the difference between the sum and the target
     */
    public int twoSumClosest(int[] nums, int target) {
        if (nums == null || nums.length < 2) {
            return -1;
        }
        Arrays.sort(nums);
        
        int left = 0;
        int right = nums.length - 1;
        int differ = Integer.MAX_VALUE;
        
        while (left < right) {
            if (nums[left] + nums[right] == target) {
                return 0;
            } else if (nums[left] + nums[right] > target) {
                differ = Math.min(differ, nums[left] + nums[right] - target);
                right--;
            } else {
                differ = Math.min(differ, target - nums[left] - nums[right]);
                left++;
            }
        } 
        
        return differ;
    }
}

你可能感兴趣的:(533.Two Sum - Closest to target)