-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3Sum_Closest.cpp
More file actions
31 lines (29 loc) · 943 Bytes
/
3Sum_Closest.cpp
File metadata and controls
31 lines (29 loc) · 943 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
29
30
31
//O(n*n)
//O(1)
class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int N = num.size();
sort(num.begin(), num.end());
int result=num[0]+num[1]+num[2];
for (int k = 0; k < N-2; k++) {
int i = k+1;
int j = N-1;
while (i < j) {
int sum = num[i] + num[j] + num[k];
if(abs(sum-target)<abs(result-target))
{
result=sum;
}
if (sum-target > 0) j--;
else if (sum-target < 0) i++;
else {
return result;
}
}
}
return result;
}
};