Wednesday, May 6, 2015

170 2Sum III - Data structure design

来源:Leetcode

原帖:https://leetcode.com/problems/two-sum-iii-data-structure-design/

题目:
Design and implement a TwoSum class. It should support the following operations: add and find.
add - Add the number to an internal data structure.
find - Find if there exists any pair of numbers which sum is equal to the value.
For example,
add(1); add(3); add(5);
find(4) -> true
find(7) -> false

代码:
 class Solution {  
 public:  
     int threeSumClosest(vector<int> &num, int target) {  
         int res = INT_MAX;  
         int N = num.size();  
         sort(num.begin(), num.end());  
         for (int i = 0; i < N - 2; ++i) {  
             int l = i + 1, r = N - 1;  
             while (l < r) {  
                 int threesum = num[i] + num[l] + num[r];  
                 if (threesum == target) {  
                     return target;  
                 } else if (threesum < target) {  
                     l++;  
                 } else {  
                     r--;  
                 }  
                 if (res == INT_MAX || abs(threesum - target) < abs(res - target)) { // trick: overflow  
                     res = threesum;  
                 }  
             }  
         }  
         return res;  
     }  
 };  

No comments:

Post a Comment