16. 3Sum Closest

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的变种, 要找离target最近的三个数的和。 跟3Sum一样这道题需要注意duplicate的处理。 先Sort下给定数组,Time为O(nlogn), 我们可以用2个全局变量一个是minNum来记录得到的sum跟target的绝对值之差,还有一个closet用来记录sum。

public class Solution {
    public int threeSumClosest(int[] nums, int target) {

        if(nums.length < 3 || nums == null) return 0;
        Arrays.sort(nums);
        int closet = 0;
        int minNum = Integer.MAX_VALUE;
        for(int i = 0; i < nums.length; i++) {
            if (i != 0 && nums[i] == nums[i - 1]) 
                continue;  // skip duplicates
            int fixed = nums[i];
            int left = i + 1;
            int right = nums.length - 1;
            while (left < right) {
                int sum = fixed + nums[left] + nums[right];
                if (Math.abs(sum - target) < minNum) {
                    minNum = Math.abs(sum - target);
                    closet = sum;
                }
                if (sum < target) {
                    left++;
                } else  {
                    right--;
                }

            }


        }
        return closet;

    }
}
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