Sunday, August 16, 2015

016 - 3Sum Closest

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

Hide Tags

Array Two Pointers

Hide Similar Problems

(M) 3Sum

貌似哈希表做这题就困难了,因为是找最靠近的,而不是确定能够等于。
双下标收拢,更新最小值即可,下标移动哪一头是依据 sum 跟 target 的大小关系来的
估计测试用例里头很多等于 target 的情况,加个等于 target 直接返回可以从 24 ms 直接提升到 12 ms.

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        int res=0, distance=INT_MAX, sz=nums.size(), sum=0;
       
        sort(nums.begin(), nums.end());
       
        for (int i = 0; i < sz-2; ++i)
        {
            int left = i + 1, right = sz - 1;
            while (left < right)
            {
                if(target == (sum= nums[i] + nums[left] + nums[right]))
                    return sum;

                int tmp = abs(sum - target);
                if (distance > tmp)
                {
                    res = sum;
                    distance = tmp;
                }
               
                (sum>target) ? (right--) : (left++);
            }
            while(i<sz-2 && nums[i]==nums[i+1])
                i++;
        }
        return res;
    }
};

12 ms.

No comments:

Post a Comment