-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy path3-sum_test.cpp
81 lines (66 loc) · 1.94 KB
/
3-sum_test.cpp
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <bits/stdc++.h>
using namespace std;
#define DEBUG(x) \
do { \
std::cout << #x << ": " << x << " "; \
} while (0)
#define DEBUGL(x) \
do { \
std::cout << #x << ": " << x << "\n"; \
} while (0)
#define MOD 1000000007
template <typename T> void print_vector(vector<T> a) {
for (auto &i : a) {
cout << i << " ";
}
cout << "\n";
}
template <typename T> void print_matrix_2d(vector<vector<T>> a) {
int r = 0;
for (auto &i : a) {
cout << r << ": ";
for (auto &j : i) {
cout << j << " ";
}
r++;
cout << "\n";
}
cout << "\n";
}
// Time - O(N^2), Space - O(1)
int solve(vector<int> &A, int B) {
vector<int> &nums = A;
int target = B;
sort(nums.begin(), nums.end());
int n = nums.size();
int result = 0;
int min_diff = INT_MAX;
for (int first = 0; first < n - 2; first++) {
int second = first + 1;
int third = n - 1;
while (second < third) {
int sum = nums[first] + nums[second] + nums[third];
int cur_diff = abs(sum - target);
if (cur_diff < min_diff) {
min_diff = cur_diff;
result = sum;
}
if (sum < target) {
second++;
} else if (sum > target) {
third--;
} else {
return sum;
}
}
}
return result;
}
int main() {
// ios::sync_with_stdio(0);
// cin.tie(0);
vector<int> nums{-1, 2, 1, -4};
int target = 1;
cout << solve(nums, target) << "\n";
return 0;
}