-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path3sumcloser.cpp
More file actions
39 lines (36 loc) · 799 Bytes
/
3sumcloser.cpp
File metadata and controls
39 lines (36 loc) · 799 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
#include<algorithm>
#include<iostream>
#include<vector>
#include<cmath>
using namespace std;
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int n=nums.size(), close=0x7fffffff;
for(int k=0; k<n; k++){
while(k>0 && k<n && nums[k] == nums[k-1])
k++;
int i=k+1, j=n-1;
while(i < j){
int sum = nums[i] + nums[j] + nums[k];
if(abs(sum - target) < close)
close = abs(sum - target);
if(sum == target){//相等,i,j为一组解,输出下标
while(i<j && nums[i] == nums[i-1])
i++;
while(i<j && nums[j] == nums[j+1])
j--;
}else if(sum > 0){//大于target,j左移
j--;
}
else{//小于target,i右移
i++;
}
}
}
return close;
}
};
int main(){
}