LeetCode16: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).
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

//要求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为止。
class Solution {
public:
	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.  

		//如果数组元素个数num.size() == 3,直接返回这3个数的和,因为只有这个解;
		if (num.size() == 3)
			return num[0] + num[1] + num[2];

		//非递减(递增)排序  
		sort(num.begin(), num.end());

		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;
			// p可以直接从i + 1位置开始,因为在i 之前的位置j 上的数如果也是解的一部分,那么在求j的时候,肯定把i位置上的数也算过了;
			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;
				}

				//移动指针进行下一步操作 ,注意在移动p和q的时候,不能等于i
				if (temp < 0)
				{
					while (++p < q && p == i)
					{
						//do nothing  
					}
				}
				else  //temp > 0  
				{
					while (--q > p && q == i)
					{
						//do nothing  
					}
				}
			}
		}

		return res;
	}
};

int main()
{
	vector<int> num1 = { -1, 2, 1,-4 };
	Solution sol;
	int t = sol.threeSumClosest(num1, 1);
	cout << t << endl;
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值