[LeetCode] 16. 3Sum Closest 解题思路
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
问题:给定一个数组和一个整数 n ,求数组中的三个元素,他们的和离 n 最近。
这道题和 3Sum 很相似,解题思路也很相似,先排序,然后采用双指针法依次比较。
由于 3Sum 很相似,思路就不详说。主要说下不同点:
- 由于是求最接近值,当 s[i] + s[l] + s[r] - target == 0 的时候,即可返回结果。
- 返回的结果是最接近 n 的三个元素之和。
1 int threeSumClosest(vector<int>& nums, int target) { 2 3 std::sort(nums.begin(), nums.end()); 4 5 int closest = target - nums[0] - nums[1] - nums[2]; 6 7 for (int i = 0 ; i < nums.size(); i++) { 8 9 int l = i + 1; 10 int r = (int)nums.size() - 1; 11 12 int newTarget = target - nums[i]; 13 14 while (l < r) { 15 if (nums[l] + nums[r] == newTarget) { 16 return target; 17 } 18 19 int diff = newTarget - nums[l] - nums[r]; 20 if (abs(diff) < abs(closest)) { 21 closest = diff; 22 } 23 24 if (nums[l] + nums[r] < newTarget){ 25 l++; 26 }else{ 27 r--; 28 } 29 } 30 } 31 32 return target - closest; 33 }