[LeetCode]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这道题很相像,这里就不说得太细了,解题思路如下:

因为要求3个数的和最接近target,所以我们先固定其中1个数,再用求“和为某值的2个数的组合”的解法,就能把剩下的2个数求出

来。此,先对数组进行非递减排序,这样整个数组的数就由小到大排列。i 的取值由 0 至 n-1,对每一个i,我们求当num[i]是解当

中的其中一个数时,其他的2个数。设有指针p指向数组头(实际只要p从i+1开始),q指向数组尾,cur = num[i] + num[p]+ num[q],那

么当前值与所求值target之间的差距就为temp = cur - target,如果abs(temp) < min,更新min = abs(temp)和当前解res = cur。

现在分为3种情况:

1. temp == 0,说明与target最接近,因为题目已经说明只有一个解,所以直接返回cur;

2. temp < 0,说明num[p]太小了,将p向后移动一个位置;

3. temp > 0,说明num[q]太大了,将q向前移动一个位置。

如此循环直到p == q为止。

 

在求解过程中,需要注意一些细节:

1. 如果数组元素个数num.size() == 3,直接返回这3个数的和,因为只有这个解;

2. 如果i != 0,而且num[i] == num[i - 1],说明刚才求过的数和现在要求的一样,没必要再重复一次,直接跳过;

3. p可以直接从i + 1位置开始,因为在i 之前的位置j 上的数如果也是解的一部分,那么在求j的时候,肯定把i位置上的数也算过了;

4. 在移动p和q的时候要注意不能等于i。

 

以下是我的代码,欢迎各位大牛指导交流~

AC,Runtime: 44 ms

 

//LeetCode_3Sum Closet
//Written by zhou
//2013.11.25

class Solution {
public:

    void swap(int &a, int &b)
    {
        int c = a;
        a = b;
        b = c;
    }

    void qsort(vector<int> &num, int left, int right)
    {
        int i = left - 1, j = right;
        int pivot = num[right];
        while(i < j)
        {
            while(++i <= right && num[i] < pivot)
            {
                //do nothing
            }
            while(--j >= left && num[j] > pivot)
            {
                //do nothing
            }
            if (i < j)
            {
                swap(num[i],num[j]);
            }
        }
        swap(num[i],num[right]);
        
        if (left < i - 1)
            qsort(num,left,i-1);
        if (i + 1 < right)
            qsort(num,i+1,right);
    }

    int threeSumClosest(vector<int> &num, int target) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        
		if (num.size() == 3)
			return num[0] + num[1] + num[2];

        //非递减(递增)排序
        qsort(num,0,num.size()-1);
        
        int min = 0x7fffffff;
        int res = 0;
        int cur = 0;
        
        for (int i = 0; i < num.size(); ++i)
        {
			//刚才找过了同值的,直接跳过
            if (i != 0 && num[i] == num[i-1])
                continue;
            
            int p = i + 1, q = num.size() - 1;
            
            while(p < q)
            {
                cur = num[i] + num[p] + num[q];

				int temp = cur - target;

				if (temp == 0)        //刚好相等直接返回
					return cur;

                if (abs(temp) < min)   //更新值
                {
                    min = abs(temp);
                    res = cur;
                }

				//移动指针进行下一步操作
				if (temp < 0)
				{
					while (++p < q && p == i)
					{
						//do nothing
					}
				}
				else  //temp > 0
				{
					while (--q > p && q == i)
					{
						//do nothing
					}
				}
            }
        }
        
        return res;
    }
};



 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值