leetcode-题7--3Sum Closest
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { int a[6] = { -1,0,1,2,-1,-4 }; vector<int>nums(a, a + 6); sort(nums.begin(), nums.end()); int tar; cin >> tar; int res = 0; int min_abs = 10000; for (auto i = nums.begin(); i < nums.end() - 2; ++i) { auto b = next(i); auto c = prev(nums.end()); while (b < c) { const int sum = *i + *b + *c; const int gab = abs(sum - tar); if (min_abs > gab) { res = sum; min_abs = gab; } if (sum > tar) c--; else b++; } } cout << res; system("pause"); return 0; }