首页 > 代码库 > 016. 3Sum Closest

016. 3Sum Closest

 1 class Solution { 2 public: 3     int threeSumClosest(vector<int>& nums, int target) { 4         sort(nums.begin(), nums.end()); 5         bool flag = false; 6         int result = 0; 7         int limit = INT_MAX; 8         for (int i = 0; i < nums.size() - 2; ++i) { 9             int j = i + 1, k = nums.size() - 1;10             //int limit = INT_MAX;11             while (j < k) {12                 int temp = nums[i] + nums[j] + nums[k];13                 if (abs(temp - target) < limit) {14                     result = temp;15                     limit = abs(temp - target);16                 }17                 if (temp > target && j < k) --k;18                 if (temp < target && j < k) ++j;19                 if (temp == target) {20                     result = temp; flag = true; break;21                 }22             }23             if (flag) break;24         }25         return result;26     }27 };

 

016. 3Sum Closest