LeetCode_3Sum Closest

 1 class Solution {

 2 public:

 3     int threeSumClosest(vector<int> &num, int target) {

 4         // Start typing your C/C++ solution below

 5         // DO NOT write int main() function

 6         sort(num.begin(), num.end());

 7         int minSum = num[0] + num[1] + num[2];

 8         int minDiff = abs(minSum - target) ;

 9         

10         for(int i =0; i< num.size() -2 ;i++){

11             int startS = i + 1 ;

12             int endS = num.size() - 1 ;

13             while(startS < endS){

14              

15              int sum = num[i] + num[startS] + num[endS];

16              int diff = abs(sum - target);

17              

18              if(diff < minDiff){

19                  minDiff = diff;

20                  minSum = sum;

21              }

22              if(sum == target) return target;

23              if(sum < target)

24                          startS ++;

25              else

26                          endS --;

27             

28             }

29         }

30         

31         return minSum;

32     }

33 };

 

你可能感兴趣的:(LeetCode)