码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode OJ:3Sum Closest(最接近的三数之和)

时间:2015-10-06 15:26:03      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

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

求三个数的和sum,使sum与target相差最小。这题实际上跟前面坐的2Sum,以及3Sum相差不是很大,大体的想法是先排序,然后外层的for循环遍历从小到大的数,然后从剩下的数中取三数之和,然后把最小的一步步保存下来,最终将最小的返回就行了。代码如下:
 1 class Solution {
 2 public:
 3     int threeSumClosest(vector<int>& nums, int target) {
 4         int sz = nums.size();
 5         sort(nums.begin(), nums.end());//当然了,首先还是要排序的
 6         int diff = INT_MAX;//这个直接取INT_MAX,这样计算出来的diff一定是比这个要小的
 7         int tmpDiff;
 8         int ans;
 9         int beg, end;
10         for (int i = 0; i < sz - 2; ++i){
11             beg = i + 1, end = sz - 1;
12             while (beg < end){
13                 int sum = nums[i] + nums[beg] + nums[end];
14                 if ((tmpDiff = abs(sum - target)) < diff){
15                     diff = tmpDiff;
16                     ans = sum;
17                 }
18                 if (sum > target){
19                     end--;
20                 }
21                 else if (sum < target){
22                     beg++;
23                 }
24                 else
25                     return sum;//相等的话就直接返回了
26             }
27         }
28         return ans;
29     }
30 };

大体上就是这样

LeetCode OJ:3Sum Closest(最接近的三数之和)

标签:

原文地址:http://www.cnblogs.com/-wang-cheng/p/4857149.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!