-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path16.cpp
More file actions
65 lines (60 loc) · 1.67 KB
/
16.cpp
File metadata and controls
65 lines (60 loc) · 1.67 KB
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
//
// 16.cpp
// LeetCode
//
// Created by 张佐玮 on 15/6/3.
// Copyright (c) 2015年 JarvisZhang. All rights reserved.
//
// Title: 3Sum Closest
//
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
if (nums.size() < 3) {
return 0;
}
int absDistance = INT_MAX, distance = 0;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size() - 2; i++) {
int start = i + 1, end = (int) nums.size() - 1;
while (start < end) {
int current = nums[i] + nums[start] + nums[end] - target;
if (current < 0) {
if (-current < absDistance) {
distance = current;
absDistance = -current;
}
start++;
}
else if (current > 0) {
if (current < absDistance) {
distance = current;
absDistance = current;
}
end--;
}
else {
return target;
}
}
}
return target + distance;
}
};
class Test {
public:
void sample() {
int input1[] = {1, 1, 1, 0}, length1 = 4, target1 = 100;
runTest(input1, length1, target1);
}
private:
static void runTest(int input[], int length, int target) {
vector<int> v(input, input + length);
Solution solution;
int result = solution.threeSumClosest(v, target);
cout << result << endl;
}
};