Monday, November 23, 2015

[leetcode]3 sum closest

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int diff = Integer.MAX_VALUE;
        for (int i = 0; i < nums.length-2; i++){
            int twoSum = twoSumClosest(nums, i+1, target-nums[i]);
            int localDiff = target-(nums[i]+twoSum);
            if (localDiff == 0){
                return target;
            }
            diff = Math.abs(diff)<Math.abs(localDiff)?diff:localDiff;
        }    
        return target+diff;
    }

    public int twoSumClosest(int[] nums, int starting, int target){
        int left = starting;
        int right = nums.length-1;
        int diff = Integer.MAX_VALUE;
        while (left < right){
            int localDiff = target-(nums[left]+nums[right]);
            if (localDiff == 0) return target;
            if (localDiff > 0) left++;
            else right--;
            diff = Math.abs(diff)<Math.abs(localDiff)?diff:localDiff;
        }
        return target+diff;
    }
}

No comments:

Post a Comment