16、3Sum Closest

2018-04-18  本文已影响0人  小鲜贝

Example

given array S = {-1 2 1 -4}, and target = 1. 
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

复杂度

时间 O(n^2) ,空间 O(1) 

解法

public class Solution {
    public int threeSumClosest(int[] nums, int target) {
        int min = Integer.MAX_VALUE;
        Arrays.sort(nums);
        
        for(int i=0;i<nums.length-2;i++){
            int temp = target - nums[i];
            int low = i+1;
            int high = nums.length-1;           
            while(low < high){
                int diff = nums[low]+nums[high]-temp;
                if(diff == 0) return target;
                if(Math.abs(min) > Math.abs(diff)){
                    min = diff;
                    }
                if(diff > 0)high--;
                else low++;
                    
            }
        }
        
        return target+min;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读