【LeetNode2-1-9】Three sum closest--C++源代码(VS2015)

来源:互联网 发布:免费邮件服务器软件 编辑:程序博客网 时间:2024/05/12 07:29
#include <iostream>
#include <math.h>
#include <unordered_map>
#include <vector>
using namespace std;

/*
three sum closest
*/

int min(int Num_A,int Num_B)
{
return Num_A > Num_B ? Num_B : Num_A;
}

void QuickSort(vector<int> &vec,int left,int right)
{
if (vec.size() <= 1)
return;
if (left > right)
return;
int first = left;
int last = right;
int key = vec[first];
while (first < last)
{
while (first < last && vec[last] > key)
{
last--;
}
vec[first] = vec[last];
while (first < last && vec[first] < key)
{
first++;
}
vec[last] = vec[first];
}
vec[first] = key;
QuickSort(vec, left, first - 1);
QuickSort(vec, first + 1, right);
}

int Solution(vector<int> &vec,const int target)
{
int result = -1;
if (vec.size() < 3)
return result;

vector<int>::iterator i = vec.begin();
vector<int>::iterator k=vec.end()-1;
result = abs(*i + *(i + 1) + *k - target);
i++;
for (; i != vec.end() - 2; i++)
{
if (i > vec.begin() && *i == *(i - 1))
continue;
vector<int>::iterator j = i + 1;
while (j < k)
{
if (*i + *j + *k < target)
{
result = min(result, abs(*i + *j + *k - target));
j++;
while (*j == *(j - 1) && j < k)
{
j++;
}
}
else if (*i + *j + *k > target)
{
result = min(result, abs(*i + *j + *k - target));
k--;
while (*k == *(k + 1) && j < k)
{
k--;
}
}
else
{
return 0;
}
}
}
return result;
}

int main()
{
int arr[] = { 2,4,6,8,1,3,5,7 };
vector<int> vec(&arr[0], &arr[8]);
QuickSort(vec,0,vec.size()-1);
int result = Solution(vec,22);
cout << "result is " << result << endl;
system("pause");
return 0;
}
阅读全文
0 0