-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy path3-sum_solve.cpp
More file actions
34 lines (29 loc) · 841 Bytes
/
Copy path3-sum_solve.cpp
File metadata and controls
34 lines (29 loc) · 841 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
// Time - O(N^2), Space - O(1)
int Solution::threeSumClosest(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;
}