Thursday, November 21, 2013

Three Sum Closest LeetCode

废话不多说,这个题跟3SUM没有任何变化,直接上code。


public int threeSumClosest(int[] num, int target) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        Arrays.sort(num);
        int smallest = Integer.MAX_VALUE;
        int closest = Integer.MAX_VALUE;
        for(int i=0; i<num.length-2; i++){
            if(i>0 && num[i]==num[i-1]) continue;
            int start = i+1;
            int end = num.length-1;
           
            while(start<end){
                int runningSum = num[i]+num[start]+num[end];
                int diff = Math.abs(runningSum - target);
                //update the smallest and colsest
                if(smallest > diff) {
                    smallest = diff;
                    closest = runningSum;
                }
                //compare with the target
                if(runningSum == target) return target;
                else if(runningSum > target) end--;
                else start++;
               
            }
        }
        return closest;
    }

No comments:

Post a Comment