Thursday, March 30, 2017

Two Sum - Closest to target

最好还是不要用Math.min()来无脑更新minDiff,感觉比较愚蠢

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) {
        // Write your code here
        if (nums == null || nums.length <= 1) return -1;
        Arrays.sort(nums);
        int minDiff = Integer.MAX_VALUE;
        int left = 0;
        int right = nums.length - 1;
        while (left < right) {
            int currSum = nums[left] + nums[right];
            if (currSum == target) return 0;
         
            int currDiff = Math.min(minDiff, Math.abs(currSum - target));
            if (currDiff < minDiff) minDiff = currDiff;
         
            if (currSum < target) {
                left++;
            } else {
                right--;
            }
        }
        return minDiff;
    }
}

No comments:

Post a Comment