-
Notifications
You must be signed in to change notification settings - Fork 0
/
three_sum_closest.cpp
99 lines (89 loc) · 2.37 KB
/
three_sum_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
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
* =====================================================================================
*
* Filename: three_sum_closest.cpp
*
* Description: 3Sum Closest: Given an array nums of n integers and an integer
* target, find three integers in nums such that the sum is closest to
* target. Return the sum of the three integers. You may assume that
* each input would have exactly one solution.
*
* Version: 1.0
* Created: 07/26/18 05:05:10
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), [email protected]
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <algorithm>
#include <vector>
class Solution
{
public:
int threeSumClosest(std::vector<int>& nums, int target)
{
if (nums.size() < 3)
{
return 0;
}
std::sort(nums.begin(), nums.end());
int closest = INT_MAX;
for (int i = 0; i < nums.size(); i++)
{
int sum = 0;
int start = i + 1;
int end = nums.size() - 1;
while (start < end)
{
sum = nums[i] + nums[start] + nums[end];
if (sum == target)
{
return target;
}
if (closest == INT_MAX)
{
closest = sum;
}
else if (std::abs(sum - target) < std::abs(closest - target))
{
closest = sum;
}
if ((sum - target) < 0)
{
start++;
}
else
{
end--;
}
}
}
return closest;
}
};
int main(int argc, char* argv[])
{
std::vector<int> nums = {-1, 2, 1, -4};
int target = 1;
if (argc > 2)
{
nums.clear();
for (int i = 1; i < argc; i++)
{
nums.push_back(atoi(argv[i]));
}
}
int closest = Solution().threeSumClosest(nums, target);
for (const auto n: nums)
{
printf("%d ", n);
}
printf("target %d, closest %d\n", target, closest);
return 0;
}