-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3SumClosest.cpp
More file actions
69 lines (67 loc) · 1.85 KB
/
Copy path3SumClosest.cpp
File metadata and controls
69 lines (67 loc) · 1.85 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
#include<iostream>
#include<algorithm>
#include<vector>
#include<climits>
#include<cmath>
using namespace std;
class Solution
{
public:
int threeSumClosest(vector<int> &num, int target)
{
if(num.empty())
return 0;
sort(num.begin(),num.end());
int minSum=0;
int close=INT_MAX;
int sum;
int n=num.size();
int i;
for(i=0; i<n-2; i++)
{
int left=i+1;
int right=n-1;
while(left<right)
{
if(num[i]+num[left]+num[right]<target)
{
sum=num[i]+num[left]+num[right];
cout<<sum<<endl;
if(target-sum<close)
{
close=target-sum;
minSum=sum;
}
left++;
}
else if(num[i]+num[left]+num[right]>target)
{
sum=num[i]+num[left]+num[right];
cout<<sum<<endl;
if(sum-target<close)
{
close=sum-target;
minSum=sum;
}
right--;
}
else if(num[i]+num[left]+num[right]==target)
{
close=0;
//cout<<"i "<<i<<" left "<<left<<" right "<<right<<endl;
//cout<<num[i]<<" "<<num[left]<<" "<<num[right]<<endl;
minSum=num[i]+num[left]+num[right];
return minSum;
}
}
}
return minSum;
}
};
int main()
{
vector<int> vec= {1,2,3,4};
Solution s;
int result=s.threeSumClosest(vec,1);
cout<<result<<endl;
}