forked from moranzcw/LeetCode-NOTES
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.cpp
More file actions
28 lines (25 loc) · 788 Bytes
/
solution.cpp
File metadata and controls
28 lines (25 loc) · 788 Bytes
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
class Solution
{
public:
int threeSumClosest(vector<int> &num, int target)
{
int closestSum = num[0]+num[1]+num[2];
sort(num.begin(),num.end());
for( int num1pos = 0; num1pos<num.size(); num1pos++ )
{
for(int num2pos=num1pos+1, num3pos=num.size()-1; num2pos < num3pos;)
{
int sum = num[num1pos] + num[num2pos] + num[num3pos];
if(sum == target)
return target;
if(abs(sum-target)<abs(closestSum-target))
closestSum = sum;
if(sum < target)
num2pos++;
else
num3pos--;
}
}
return closestSum;
}
};