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

leetcode 3Sum Closest

时间:2015-04-14 22:50:51      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

代码:

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<vector>
 4 
 5 using namespace std;
 6 
 7 int threeSumClosest(vector<int> &num, int target) {
 8     sort(num.begin(),num.end());
 9     int L = num.size();
10     int min = INT_MAX;
11     int beauty;
12     for (int i = 0; i < L-2; i++)
13     {
14         int l = i + 1;
15         int r = L - 1;
16         int sum = num[l]+num[r]+num[i];
17         while (l < r)
18         {
19             sum = num[l] + num[r] +num[i];
20             if (abs(target - sum) < min)
21             {
22                 min = abs(target - sum);
23                 beauty = sum;
24             }
25             if (sum < target)
26             {
27                 l++;
28             }
29             else if (sum > target)
30             {
31                 r--;
32             }
33             else
34             {
35                 return sum;
36             }
37         }
38     }
39     return beauty;
40 }
41 
42 
43 
44 int main()
45 {
46     vector<int> S = { 87, 6, -100, -19, 10, -8, -58, 56, 14, -1, -42, -45, -17, 10, 20, -4, 13, -17, 0, 11, -44, 65, 74, -48, 30, -91, 13, -53, 76, -69, -19, -69, 16, 78, -56, 27, 41, 67, -79, -2, 30, -13, -60, 39, 95, 64, -12, 45, -52, 45, -44, 73, 97, 100, -19, -16, -26, 58, -61, 53, 70, 1, -83, 11, -35, -7, 61, 30, 17, 98, 29, 52, 75, -73, -73, -23, -75, 91, 3, -57, 91, 50, 42, 74, -7, 62, 17, -91, 55, 94, -21, -36, 73, 19, -61, -82, 73, 1, -10, -40, 11, 54, -81, 20, 40, -29, 96, 89, 57, 10, -16, -34, -56, 69, 76, 49, 76, 82, 80, 58, -47, 12, 17, 77, -75, -24, 11, -45, 60, 65, 55, -89, 49, -19, 4 };
47     cout << threeSumClosest(S,-275) << endl;
48     return 0;
49 }

 

leetcode 3Sum Closest

标签:

原文地址:http://www.cnblogs.com/chaiwentao/p/4426270.html

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