LeetCode 16. 3Sum Closest(双指针)

题目来源:https://leetcode.com/problems/3sum-closest/

问题描述

16. 3Sum Closest

Medium

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

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

 

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

------------------------------------------------------------

题意

给出一组整数序列和一个整数target,求序列中三个数的和sum3,使得sum3尽量靠近target.

------------------------------------------------------------

思路

问题可以转化为给定一个数a,求序列中另外两个数b, c,使得b + c尽量接近target-a.

上一题一样,仍是采用双指针法。

将输入无序序列排序,对于序列中的每个a,问题转化为求a右侧的数对,使得数对的和尽量接近target-a. 有序序列数对求和逼近固定值问题用双指针法可以用O(n)解决,基本代码同零和问题一样,只是多加一个对最小差值的维护。总的复杂度也是O(n^2).

------------------------------------------------------------

代码

class Solution {
    public final int INF = (1<<30);
    public int threeSumClosest(int[] nums, int target) {
        int n = nums.length, i = 0, left = 0, right = n - 1, sum = 0, expected = -1, min_gap = INF, sum3 = 0, gap = 0;
        if (n < 3)              // invalid input
        {
            return 0;
        }
        Arrays.sort(nums);
        for (i=0; i<n-2; i++)
        {
            if (i > 0 && nums[i] == nums[i-1])
            {
                continue;
            }
            left = i + 1;
            right = n - 1;
            expected = target - nums[i];
            while (left < right)
            {
                sum = nums[left] + nums[right];
                if (sum == expected)
                {
                    return target;
                }
                else if (sum < expected)
                {
                    gap = expected - sum;
                    if (gap < min_gap)
                    {
                        min_gap = gap;
                        sum3 = sum + nums[i];
                    }
                    while (left < n-1 && nums[left] == nums[++left]);
                }
                else
                {
                    gap = sum - expected;
                    if (gap < min_gap)
                    {
                        min_gap = gap;
                        sum3 = sum + nums[i];
                    }
                    while (right > 0 && nums[right] == nums[--right]);
                }
            }
        }
        return sum3;
    }
}

猜你喜欢

转载自blog.csdn.net/da_kao_la/article/details/88345153