// 3sumclosest. cpp: defines the entry point of the console application. // # 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 ;}
[Leetcode] 3 Sum closet