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

[LeetCode 16] 3Sum Closest

时间:2015-03-01 22:18:41      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:

算法渣,现实基本都参考或者完全拷贝[戴方勤(soulmachine@gmail.com)]大神的leetcode题解,此处仅作刷题记录。

 

 1 class Solution {
 2 public:
 3     int threeSumClosest(vector<int> &num, int target) {
 4         int result = 0;
 5         int min_gap = INT_MAX;
 6 
 7         sort(num.begin(), num.end()); // 排序
 8 
 9         auto last = num.end();
10         for (auto a = num.begin(); a < prev(last, 2); ++a) {
11             auto b = next(a);
12             auto c = prev(last);
13             while (b < c) {
14                 const int sum = *a + *b + *c;
15                 const int gap = abs(sum - target);
16 
17                 if (gap < min_gap) {
18                     result = sum;
19                     min_gap = gap;
20                 }
21 
22                 if (sum < target)
23                     ++b;
24                 else
25                     --c;
26             }
27         }
28 
29         return result;
30     }
31 };

 

[LeetCode 16] 3Sum Closest

标签:

原文地址:http://www.cnblogs.com/Azurewing/p/4307611.html

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