016. 3Sum Closest

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

leetcode_016 3Sum Closest(TwoPointers)

3Sum Closest

leetcode16 3Sum Closest

16. 3Sum Closest

16. 3Sum Closest

Leetcode 16. 3Sum Closest