-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy path3Sum Closest.cpp
More file actions
42 lines (40 loc) · 1.07 KB
/
3Sum Closest.cpp
File metadata and controls
42 lines (40 loc) · 1.07 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
class Solution
{
public:
int threeSumClosest(vector<int> &num, int target)
{
int closest = 0;
if (num.size() >= 3)
{
sort(num.begin(), num.end());
closest = num[0] + num[1] + num[2];
for (size_t i = 0; i + 2 < num.size(); ++i)
{
size_t j = i + 1;
size_t k = num.size() - 1;
while (j < k)
{
int sum = num[i] + num[j] + num[k];
if (abs(sum - target) < abs(closest - target))
{
closest = sum;
}
if (sum < target)
{
++j;
}
else if (sum > target)
{
--k;
}
else
{
++j;
--k;
}
}
}
}
return closest;
}
};