-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreeSumClosest.cpp
More file actions
50 lines (43 loc) · 1.14 KB
/
threeSumClosest.cpp
File metadata and controls
50 lines (43 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <vector>
#include <math.h>
#include <algorithm>
using namespace std;
class Solution
{
public:
int threeSumClosest(vector<int> &nums, int target)
{
//双指针
sort(nums.begin(),nums.end());
int clothestNum1 = 99999;
for (int i = 0; i < nums.size() - 2; i++)
{
//外面只定义指针,运算更新要在指针运算外
int left = i + 1;
int right = nums.size() - 1;
while(left < right)
{
int sum = nums[left] + nums[right] + nums[i];
int gap = abs(sum - target);
if(gap < abs(clothestNum1 - target))
{
clothestNum1 = sum;
}
if (clothestNum1 == target)
{
return target;
}
//移动指针相关逻辑
if(sum < target)
{
left++;
}
else
{
right--;
}
}
}
return clothestNum1;
}
};