LeetCode16. 3Sum Closest(C++)
阿新 • • 發佈:2019-01-14
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).
解題思路:與15題l類似,先確定一個數,然後雙指標法
class Solution { public: int threeSumClosest(vector<int>& nums, int target) { sort(nums.begin(),nums.end()); if(nums.size()<3) return 0; int result=nums[0]+nums[1]+nums[2],resultmin=abs(result-target); for(int i=0;i<nums.size()-2;i++){ while(i!=0&&nums[i]==nums[i-1]) i++; int low=i+1,high=nums.size()-1; while(low<high){ int temp=nums[i]+nums[low]+nums[high]; if(abs(temp-target)<resultmin){ resultmin=abs(temp-target); result=temp; } if(resultmin==0) break; else if(temp<target) low++; else high--; } } return result; } };