美文网首页
16、3Sum Closest

16、3Sum Closest

作者: 小鲜贝 | 来源:发表于2018-04-18 14:05 被阅读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;
    }
}

相关文章

网友评论

      本文标题:16、3Sum Closest

      本文链接:https://www.haomeiwen.com/subject/blpvkftx.html