3Sum Closest, Leetcode 解题笔记

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

For 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).

这道题同属3Sum系列,换汤不换药,同样是先排序数组,假设三个数是n1,n2,和n3。然后每次遍历一个数作为n1,然后再这个数右边的子数组中从左右两头往中间找。相对3Sum要简单,因为题目已经帮我们排除了重复的solution。

public class Solution {
    public int threeSumClosest(int[] num, int target) {
        if(num.length < 3) return 0;
        Arrays.sort(num);
        int min_value = Integer.MAX_VALUE;
        int min_sum = 0;
        
        for(int i = 0; i < num.length-2; i++){
            int left = i + 1;
            int right = num.length -1;
            while(left < right){
                int sum = num[i] + num[left] + num[right];
                if(Math.abs(sum - target) < min_value){
                    min_value = Math.abs(sum-target);
                    min_sum = sum; 
                }
                if(sum < target){
                    left++;
                }
                else if(sum > target){
                    right--;
                }
                else{
                    return target;
                }
            }
        }
        
        return min_sum;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s