0016.cpp (600B)
1 class Solution { 2 public: 3 int threeSumClosest(vector<int> &nums, int target) { 4 int n = nums.size(), delta = INT_MAX / 2, res = 0; 5 sort(nums.begin(), nums.end()); 6 for (int i = 0; i < n; i++) { 7 int j = i + 1; 8 int k = n - 1; 9 while (j < k) { 10 int sum = nums[i] + nums[j] + nums[k]; 11 if (abs(target - sum) < delta) { 12 delta = abs(target - sum); 13 res = sum; 14 } 15 (sum > target) ? k-- : j++; 16 } 17 } 18 return res; 19 } 20 };