daily pastebin goal
16%
SHARE
TWEET

Untitled

a guest Nov 22nd, 2017 49 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. int threeSumClosest(vector<int> &numbers, int target) {
  2.     // write your code here
  3.     if (numbers.size() < 3) return 0;
  4.  
  5.     int closestSum = INT_MAX;
  6.     sort(numbers.begin(), numbers.end());
  7.     for (int i=0; i<numbers.size()-2; i++) {
  8.         int left = i+1;
  9.         int right = numbers.size()-1;
  10.  
  11.         while (left < right) {
  12.             int sum = numbers[i] + numbers[left] + numbers[right];
  13.             if (sum == target) {
  14.                 return target;
  15.             } else if (sum < target) {
  16.                 left += 1;
  17.             } else {
  18.                 right -= 1;
  19.             }
  20.  
  21.             if (abs(target - sum) < abs(target - closestSum)) {
  22.                 closestSum = sum;
  23.             }
  24.         }
  25.     }
  26.  
  27.     return closestSum;
  28. }
RAW Paste Data
Top