-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3SumClosest.cpp
More file actions
executable file
·71 lines (59 loc) · 1.63 KB
/
3SumClosest.cpp
File metadata and controls
executable file
·71 lines (59 loc) · 1.63 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
66
67
68
69
70
71
//
// 3SumClosest.cpp
// leetcode
//
// Created by witwolf on 5/2/15.
// Copyright (c) 2015 witwolf. All rights reserved.
//
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <utility>
using namespace std;
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
size_t i,j,k;
int sumClosest = nums[0] + nums[1] + nums[2];
for(i=1; i<nums.size()-1; ++i){
j = 0;
k = nums.size() - 1;
while(j<i && k >i){
int sum = nums[i] + nums[j] + nums[k];
if(sum == target){
return sum;
}else if(sum > target){
--k ;
}else{
++j;
}
if(abs(sum-target) < abs(sumClosest-target)){
sumClosest = sum;
}
}
}
return sumClosest;
}
};
int main(int argc,char **argv){
Solution s;
srand(time(0));
int n = 100 ;
while(n--){
int numSize = rand() % 20 ;
if (numSize > 0){
int target = rand() % 1000;
vector<int> nums ;
nums.resize(numSize);
for(int i = 0;i<numSize;++i){
nums[i] = rand() % 1000;
}
cout << "Nums: " ;
copy(nums.begin(),nums.end(),ostream_iterator<int>(cout," "));
cout << ", Target :" << target << ",answer:" << s.threeSumClosest(nums,target) << endl;
}
}
}