标签:blog io os ar for sp div on log
// 3SumClosest.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <vector> #include<cstdlib> #include <iostream> #include <algorithm> using namespace std; class Solution { public: int threeSumClosest(vector<int> &num, int target) { int closet = 999999; sort(num.begin(),num.end()); for (int i = 0; i < num.size()-2; i++) { if (i>0 && num[i] == num[i - 1]) continue; int p1 = i + 1, p2 = num.size() - 1; while (p1 < p2) { if (p1>i + 1 && num[p1] == num[p1 - 1]) { p1++; continue; } if (p2 < num.size() - 1 && num[p2] == num[p2 + 1]) { p2--; continue; } if (p1>p2) break; int sum = num[i] + num[p1] + num[p2]; if (sum == target) { p2--; closet = target; } else if (sum<target) { p1++; if (abs(sum - target) < abs(closet - target)) { closet = sum; } } else { p2--; if (abs(sum - target) < abs(closet - target)) { closet = sum; } } } } return closet; } }; int _tmain(int argc, _TCHAR* argv[]) { Solution ss; vector<int>test; test.push_back(1); test.push_back(1); test.push_back(1); test.push_back(0); //test.push_back(-4); int sum = ss.threeSumClosest(test,100); cout << sum << endl; system("pause"); return 0; }
标签:blog io os ar for sp div on log
原文地址:http://www.cnblogs.com/supernigel/p/4029705.html