-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3SumClosest.cc
More file actions
51 lines (41 loc) · 876 Bytes
/
Copy path3SumClosest.cc
File metadata and controls
51 lines (41 loc) · 876 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <limits.h>
#include <math.h>
#include <memory.h>
#include <sstream>
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
int min = INT_MAX;
int result = 0;
sort(num.begin(), num.end() );
for (int i = 0; i < num.size(); i++) {
int j = i + 1;
int k = num.size() - 1;
while (j < k) {
int sum = num[i] + num[j] + num[k];
int diff = abs(sum - target);
if (diff == 0) return target;
if (diff < min) {
min = diff;
result = sum;
}
if (sum <= target) {
j++;
} else {
k--;
}
}
}
return result;
}
};
int main(int argc, char const *argv[]) {
/* code */
return 0;
}