Given an array nums
of n integers and an integer target
, find three integers in nums
such that the sum is closest to target
. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
code
#include <iostream> #include <vector> #include <algorithm> #include <iterator> using namespace std; class Solution { public: int threeSumClosest(vector<int>& nums, int target) { if(nums.size()<3) return 0; int res=0x3f3f; vector<int> tmp(nums); sort(tmp.begin(),tmp.end()); //copy(tmp.begin(),tmp.end(),ostream_iterator<int>(cout," ")); //cout<<endl; for(int i=0;i<tmp.size();++i) { int t=tmp.at(i); int l=i+1; int r=tmp.size()-1; while(l<r) { //-3 0 1 2 int k=tmp.at(l); int s=tmp.at(r); int sum=t+tmp.at(l)+tmp.at(r); res=abs(res-target)<abs(sum-target)?res:sum; if(l<r&&sum<target) ++l; else if(l<r&&sum>target) --r; else return target; /* while(l<r&&tmp.at(r)==tmp.at(r-1)) --r; while(l<r&&tmp.at(l)==tmp.at(l+1)) ++l; ++l; --r;*/ } } return res; } }; int main() { Solution s; vector<int> arr{0,2,1,-3}; cout<<s.threeSumClosest(arr,1)<<endl; return 0; }