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).
想法:与之前的类似,使用双指针,另外设立一个变量去保存最接近target的值
class Solution { public: int threeSumClosest(vector<int>& nums, int target) { int len = nums.size(); if( 3 > len) return 0; int temp = nums.at(0) + nums.at(1) + nums.at(2); sort(nums.begin(),nums.end()); for(int i = 0 ; i < len-2 ; i++){ if(i != 0 && nums[i] == nums[i-1]) continue; int left = i + 1; int right = len - 1; while(left < right){ int sum = nums.at(i) + nums.at(left) + nums.at(right); if(sum == target) return sum; if(abs(sum - target) < abs(temp - target)){ temp = sum; } if(sum < target){ left++; }else{ right--; } } } return temp; } };