[LeetCode] 3Sum Closest

This problem is very similar to 3Sum. You only need to maintain a variable for the sum that is closet to target. Also, some corner cases need to be handled; for example, nums does not have more than 2 elements.

The code is as follows, which is quite self-explanatory.

 1     int threeSumClosest(vector<int>& nums, int target) {
 2         sort(nums.begin(), nums.end());
 3         while (nums.size() <= 2)
 4             return accumulate(nums.begin(), nums.end(), 0);
 5         int ans = nums[0] + nums[1] + nums[2];
 6         for (int i = 0; i < nums.size() - 2; i++) {
 7             int left = i + 1, right = nums.size() - 1;
 8             while (left < right) {
 9                 int temp = nums[i] + nums[left] + nums[right];
10                 if (abs(temp - target) < abs(ans - target))
11                     ans = temp;
12                 if (temp == target) return ans;
13                 if (temp > target) right--;
14                 else left++;
15             }
16         }
17         return ans;
18     }
原文地址:https://www.cnblogs.com/jcliBlogger/p/4567740.html