标签:
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Array Two Pointers
#include <iostream> #include <vector> #include <algorithm> using namespace std; class Solution { public: int threeSumClosest(vector<int> &num, int target) { if(num.size()<4){ int retNum=0; for(int i=0;i<num.size();i++) retNum += num[i]; return retNum; } vector<int> tmpnum = num; sort(tmpnum.begin(),tmpnum.end()); // for(int i=0;i<tmpnum.size();i++) // cout<<tmpnum[i]<<" "; // cout<<endl; int retNum = tmpnum[0]+tmpnum[1]+tmpnum[2]; for(int outIdx = 0;outIdx<tmpnum.size();outIdx++){ int intarget = target-tmpnum[outIdx]; for(int inleft=0,inright=num.size()-1;inleft<inright;){ if(inleft==outIdx){ inleft++; continue; } if(inright==outIdx){ inright--; continue; } // cout<<tmpnum[inleft]<<" "<<tmpnum[inright]<<endl; if(abs(tmpnum[inleft]+tmpnum[inright] + tmpnum[outIdx]-target)<abs(retNum-target) ) retNum = tmpnum[inleft]+tmpnum[inright] + tmpnum[outIdx]; if(tmpnum[inleft]+tmpnum[inright]<intarget) inleft++; else if(tmpnum[inleft]+tmpnum[inright]>intarget) inright--; else return retNum; } } return retNum; } }; int main() { vector<int > num{1,1,-1,-1,3}; Solution sol; cout<<sol.threeSumClosest(num,-1)<<endl; return 0; }
标签:
原文地址:http://www.cnblogs.com/Azhu/p/4332934.html