LintCode 59: 3Sum Closest

  1. 3Sum Closest
    中文English
    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.

Example
Example 1:

Input:[2,7,11,15],3
Output:20
Explanation:
2+7+11=20
Example 2:

Input:[-1,2,1,-4],1
Output:2
Explanation:
-1+2+1=2
Challenge
O(n^2) time, O(1) extra space

Notice
You may assume that each input would have exactly one solution.

解法1:类似3sum,只是每次都要更新result。
代码如下:

class Solution {
public:
    /**
     * @param numbers: Give an array numbers of n integer
     * @param target: An integer
     * @return: return the sum of the three integers, the sum closest target.
     */
    int threeSumClosest(vector<int> &numbers, int target) {
        int N = numbers.size();
        if (N < 3) return 0;
        
        sort(numbers.begin(), numbers.end());
        
        int p1 = 0, p2 = 0, p3 = 0;
        int result = numbers[0] + numbers[1] + numbers[2];
        
        for (int p3 = 3; p3 < N; ++p3) {
            int newTarget = target - numbers[p3];
            p1 = 0, p2 = p3 - 1;
            while(p1 < p2) {
                int twoSum = numbers[p1] + numbers[p2];
                int threeSum = twoSum + numbers[p3];
                
                if (abs(result - target) > abs(threeSum - target)) {
                    result = threeSum;
                } 
                
                if (twoSum < newTarget) {
                    p1++;
                } else if (twoSum > newTarget) {
                    p2--;
                } else {
                    break;
                }
            }
        }
        
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值