Leetcode016 3Sum Closest

public class S016 {
    //借鉴S015的思想,只是稍微有点慢
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int result = nums[0]+nums[1]+nums[nums.length-1];
        for(int i =0;i<nums.length;i++){
            if(i>0&&nums[i]==nums[i-1])
                continue;
            int left = i+1;
            int right = nums.length-1;
            while(left<right){
                if(nums[i]+nums[left]+nums[right]==target){
                    result = nums[i]+nums[left]+nums[right];
                    return result;//如果只是break;会产生不必要的for循环,影响速度
                }else{
                    result = Math.abs(nums[i]+nums[left]+nums[right]-target)<Math.abs(result-target)?
                            (nums[i]+nums[left]+nums[right]):result;                            
                    if(nums[i]+nums[left]+nums[right]<target){
                        left++;
                        while(left<right&&nums[left] == nums[left-1]){
                            left++;
                        }                        
                    }else if(nums[i]+nums[left]+nums[right]>target){
                        right--;
                        while(left<right&&nums[right] == nums[right+1]){
                            right--;
                        }                        
                    }
                }
            }
        }
        return result;
    }
}

 

posted @ 2016-03-11 20:12  fisherinbox  阅读(160)  评论(0编辑  收藏  举报