LeetCode - 3Sum Closest

converse the question to :

  find the minimum of (3Sum-target). We can also put the (-target) to the array~

similar to the 3Sum,only change the find condition a bit! 

Note: assume that each input would have exactly one solution

 

Time Complexity: O(n^2)

Space Complexity: O(1)

 1 bool compare(const int& a, const int& b)
 2 {
 3       return (a<b);
 4 }
 5 
 6 
 7 class Solution {
 8 
 9 
10 public:
11     int threeSumClosest(vector<int> &num, int target) {
12         // Start typing your C/C++ solution below
13         // DO NOT write int main() function
14         
15         std::sort(num.begin(), num.end(), compare);
16         
17         int len = num.size();
18         if(len == 1)    return num[0];
19         
20         int minsum = 0x8fffffff;
21         int tmpsum, tmp;
22         int pl, pr;
23                 
24         for(int i=0; i<len; i++)
25         {
26             pl = i+1;
27             pr = len-1;
28             
29             while(pl < pr)
30             {
31                 tmpsum = num[pl]+num[pr]+num[i];
32                 
33                 if(tmpsum == target)    return target; 
34                 
35                 if( abs(tmpsum-target) < abs(minsum-target) )
36                     minsum = tmpsum;
37                 
38                 if(tmpsum < target)    pl++;
39                 else    pr--;    
40             }
41         }
42         
43         return minsum;
44     }
45 };

 

References:

http://blog.csdn.net/li4951/article/details/8693212

 

 

 

posted on 2013-05-03 19:45  highstar88  阅读(215)  评论(0编辑  收藏  举报

导航