-
Notifications
You must be signed in to change notification settings - Fork 52
/
3Sum Closest.cpp
34 lines (30 loc) · 904 Bytes
/
3Sum Closest.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
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int ans = 0;
int diff = INT_MAX;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); i++) {
if (i > 0 && nums[i - 1] == nums[i]) {
continue;
}
int j = i + 1;
int k = nums.size() - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
if (abs(sum - target) < diff) {
ans = sum;
diff = abs(sum - target);
}
if (sum < target) {
j++;
} else if (sum > target) {
k--;
} else {
return target;
}
}
}
return ans;
}
};