欢迎来到IT嘟嘟的博客

人生三从境界:昨夜西风凋碧树,独上高楼,望尽天涯路。 衣带渐宽终不悔,为伊消得人憔悴。 众里寻他千百度,蓦然回首,那人却在灯火阑珊处。
扩大
缩小

16. 最接近的三数之和

给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。

返回这三个数的和。假定每组输入只存在唯一答案。

例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.

与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

 

/*
解题思路:
最接近于给定值的值,即我们要保证当前三数和跟给定值之间的差的绝对值最小,
所以我们需要定义一个变量 temp2用来记录差的绝对值,然后我们还是要先将数组排个序,
然后开始遍历数组。
*/

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
	int threeSumClosest(vector<int>& nums, int target)
	{
		sort(nums.begin(), nums.end());
		int len = nums.size();
		int result;
		int temp1, temp2;
		int min = abs(nums[0] + nums[1] + nums[2] - target);
		for (int i = 0; i < len - 2; i++)
		{
			for (int j = i + 1; j < len - 1; j++)
			{
				for (int k = j + 1; k < len; k++)
				{
					temp1 = nums[i] + nums[j] + nums[k];
					temp2 = abs(temp1 - target);
					if (temp2 <= min)
					{
						min = temp2;
						result = temp1;
					}
				}
			}
		}
		return result;
	}
};
int main(){
	vector<int>nums;
	int target;
	cin >> target;
	int a[1000];
	int i = 0;
	int x;
	while (cin >> a[i])
	{
		x = cin.get();
		if (x == '\n')
			break;
		nums.push_back(a[i]);
		++i;
	}	
	cout << Solution().threeSumClosest(nums, target) << endl;
	system("pause");
	return 0;

}

  

  

posted on 2019-08-23 19:13  IT嘟嘟  阅读(241)  评论(0)    收藏  举报

导航