您的位置:首页 > 编程语言 > C语言/C++

C++实现LeetCode(三个数的和最接近目标数)

2017-08-14 19:06 525 查看
Leetcode:16题:

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


翻译一下:大概的意思是,从一数组中,抽取三个数并求和,使之更接近与我们所给的target数(相等是最好的),然后返回三个数的和。

思路分析:

定义一个初始对比数dif:本代码为前三个数的和。

先固定第一个数first,第二个数second为first的下一个数,即first+1(!!!注意!!!,这里的first和second是下标),然后让第三个数third从数组的尾部向前遍历,然后求这三个数的和sum,并与target做差,如果小于dif与target的差,则令dif=sum。如果sum-target=0,则直接返回sum。如果是其他情况,则让third继续遍历,当遍历完third,再让second遍历,如此下去,直到second也遍历完,然后进行i=i+1,即first遍历下一个数。

相应的代码如下:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
std::sort(nums.begin(),nums.end());
int dif = nums[0] + nums[1] + nums[2];//初始定义前三个是最接近的,也可以定义其他。
if (nums.size() < 3) return 0;//如果不足三个数,肯定不满足我们的题目,所以返回0。
for (int i = 0; i < nums.size()-2; i++)
{
//for循环里面的判断条件是num.size()-2,因为i是三个数中的第一个数,如果i是num.size()-1,那么第三个数就会超出数组范围。
int first = i;
int second = first + 1;
int third = nums.size()-1;//从后往前遍历,也可以从前往后,但是这个时候,当second遍历下一个数时,third就必须从second后一位开始遍历。 用third=nums.size()-1 可以避免这一步。

while (second<third) {
int sum = nums[first] + nums[second] + nums[third];
if (sum == target) return sum;
if (abs(sum-target) < abs(dif-target))
dif = sum;
if (sum > target)
--third;
else
++second;
}
}
return dif;
}
};
int main()
{
Solution s;
vector<int> A{ -1,2,1,4};
cout << s.threeSumClosest(A,2);
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息