首页 > 其他 > 详细

【Leetcode】3Sum Closest

时间:2014-03-18 12:08:57      阅读:419      评论: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).
bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     int threeSumClosest(vector<int>& num, int target) {
 4         int result = 0;
 5         int min_gap = INT_MAX;
 6         sort(num.begin(), num.end());
 7         for (size_t i = 0; i < num.size() - 2; ++i) {
 8             if (i > 0 && num[i] == num[i - 1]) continue;
 9             size_t j = i + 1, k = num.size() - 1;
10             while (j < k) {
11                 int sum = num[i] + num[j] + num[k];
12                 int gap = abs(sum - target);
13                 if (gap < min_gap) {
14                     min_gap = gap;
15                     result = sum;
16                 }
17                 if (sum < target) {
18                     ++j;
19                 } else if (sum > target) {
20                     --k;
21                 } else {
22                     return result;
23                 }
24             }
25         }
26         return result;
27     }
28 };
View Code

与上题3Sum类似,先排序,然后以一个元素为准,两边夹逼,逐个求三个元素的和,找到与目标相等的了可以直接返回,对于重复元素可以只找一次。

【Leetcode】3Sum Closest,布布扣,bubuko.com

【Leetcode】3Sum Closest

原文:http://www.cnblogs.com/dengeven/p/3606227.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!