16. 3Sum Closest

2018-02-07  本文已影响0人  wtmxx

3Sum思路相同

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        int mindis = Integer.MAX_VALUE;
        Arrays.sort(nums);
        int sum = 0;
        int len = nums.length;
        
        for(int i=0;i<len-2;i++){
            while(i>0&&i<len-2&&nums[i]==nums[i-1])i++;
            int p = i+1,q = len-1;
            while(p<q){
                int tmp = nums[i]+nums[p]+nums[q]-target;
                if(Math.abs(tmp)<mindis){
                    mindis = Math.abs(tmp);
                    sum = tmp+target;
                }
                if(tmp<0){
                    p++;
                }else if(tmp>0){
                    q--;
                }else{
                    return target;
                }
            }
        }
        return sum;
    }
}
上一篇下一篇

猜你喜欢

热点阅读