2016年6月23日星期四

[LintCode] #59 3Sum Closest

Thinking:
1) triple for loop -> sum nearest to target O(n^3)
2) sort +  search for closest -> sum nearest to target O(n^2)
3) impossible to be done in O(n) :p

public class Solution {
    public int threeSumClosest(int[] nums, int target) {
        if (nums == null || nums.length < 3) {
            return 0;
        }
        
        Arrays.sort(nums);
        
        int closest = nums[0] + nums[1] + nums[2];
        for (int i = 0; i < nums.length; i++) {
            int start = i + 1;
            int end = nums.length - 1;
            
            while (start < end) {
                int sum = nums[i] + nums[start] + nums[end];
                if (sum == target) {
                    return sum;
                } else if (sum < target) {
                    start++;
                } else {
                    end--;
                }
                
                if (Math.abs(sum - target) < Math.abs(closest - target)) {
                    closest = sum;
                }
            }
        }
        
        return closest;
    }
}


没有评论:

发表评论