Advertisement
nikunjsoni

16

Apr 15th, 2021
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.89 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int threeSumClosest(vector<int>& nums, int target) {
  4.         if(nums.size() < 3) return 0;
  5.         int closest = nums[0]+nums[1]+nums[2];
  6.         sort(nums.begin(), nums.end());
  7.         for(int first = 0 ; first < nums.size()-2 ; ++first) {
  8.             if(first > 0 && nums[first] == nums[first-1]) continue;
  9.             int second = first+1;
  10.             int third = nums.size()-1;            
  11.             while(second < third) {
  12.                 int curSum = nums[first]+nums[second]+nums[third];
  13.                 if(curSum == target) return curSum;
  14.                 if(abs(target-curSum)<abs(target-closest)) {
  15.                     closest = curSum;
  16.                 }
  17.                 if(curSum > target) {
  18.                     --third;
  19.                 } else {
  20.                     ++second;
  21.                 }
  22.             }
  23.         }
  24.         return closest;
  25.     }
  26. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement