leetcode-16-数组题-最接近的三数之和

题目

1.png

解法

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
// 排序 + 双指针

class Solution {
public:
void changePosAdd(int &pos, vector<int>& nums, int n){
while((pos + 1 < n) && (nums[pos + 1] == nums[pos]))
++pos;
++pos;
}

void changePosSub(int &pos, vector<int>& nums){
while((pos - 1 > 0) && (nums[pos - 1] == nums[pos]))
--pos;
--pos;
}

int threeSumClosest(vector<int>& nums, int target) {
int n = nums.size();
if (n < 3)
throw "the size of nums must bigger than 3";

sort(nums.begin(), nums.end());
int diff = 32765;
int res;
int now = 0;
while(now < n-2){
int low = now + 1;
int high = n - 1;
while(low < high){
int tempSum = nums[now] + nums[low] + nums[high];
int tempDiff = tempSum - target;
if(abs(tempDiff) < diff){
diff = abs(tempDiff);
res = tempSum;
}
if(tempDiff == 0){
return res;
}else if(tempDiff > 0){
changePosSub(high, nums);
}else{
changePosAdd(low, nums, n);
}
}

changePosAdd(now, nums, n);
}

return res;
}
};