题目:最接近的三数之和
与上一题(15题)一样,使用的是双指针与双循环,这样可以将O(n^3)的时间复杂度降低至O(n^2)
最后判断当前的和与目标值的大小关系,如果更小,说明需要找到更大的数,因此将左指针右移,反之,将右指针左移
1int threeSumClosest(vector<int>& nums, int target)
2 {
3 int length = nums.size();
4 std::sort(nums.begin(), nums.end());
5 int closest_sum = nums[0] + nums[1] + nums[2];
6
7 for(int i = 0; i < length - 2; i++)
8 {
9 int left = i + 1, right = length - 1;
10 while(left < right)
11 {
12 int current_sum = nums[i] + nums[left] + nums[right];
13 if(current_sum == target) return current_sum;
14 if(std::abs(current_sum - target) < std::abs(closest_sum - target))
15 closest_sum = current_sum;
16 if(current_sum < target)
17 left++;
18 else
19 right--;
20 }
21 }
22 return closest_sum;
23 }
来源:语雀原笔记