16. 最接近的三数之和
给你一个长度为n
的整数数组 nums
和 一个目标值 target
。请你从 nums
中选出三个整数,使它们的和与 target
最接近。
返回这三个数的和。
假定每组输入只存在恰好一个解。
示例 1:
输入:nums = [-1,2,1,-4], target = 1 输出:2 解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
示例 2:
输入:nums = [0,0,0], target = 1 输出:0
提示:
3 <= nums.length <= 1000
-1000 <= nums[i] <= 1000
-104 <= target <= 104
和上一个很像,可参考三数之和,所以直接来
1 class Solution { 2 public: 3 int threeSumClosest(vector<int>& nums, int target) { 4 sort(nums.begin(),nums.end()); 5 int len=nums.size(); 6 int res=0; 7 int minus=10010; 8 for(int i=0;i<len;i++){ 9 int td=len-1; 10 if(i==0||nums[i]!=nums[i-1]){ 11 for(int j=i+1;j<len;j++){ 12 if(j==i+1||nums[j]!=nums[j-1]){ 13 14 while(td>j){ 15 int now=(nums[i]+nums[j]+nums[td]); 16 if(now<=target){//如果小那么前面更小就直接跳出 17 if(abs(now-target)<minus){ 18 res=now; 19 minus=abs(now-target); 20 } 21 break; 22 }else{ 23 if(abs(now-target)<minus){//如果大就每次都记录和左移 24 res=now; 25 minus=abs(now-target); 26 } 27 td--; 28 } 29 } 30 31 } 32 33 } 34 } 35 } 36 return res; 37 } 38 };
耗时比较高,看了一下大神写的,去掉了second的循环,将second和third变成while里面的 l 和 r ,
即 L<r 时,如果当前和>target, r 就左移,和就变小了;
如果和>target,l 右移,和就变大了;
如果相等就跳出。
1 class Solution { 2 public: 3 int threeSumClosest(vector<int>& nums, int target) { 4 int res = 99999; 5 int rr = 0; 6 sort(nums.begin(), nums.end()); 7 8 for (int first = 0; first < nums.size(); first++) 9 { 10 int second = first + 1; 11 int third = nums.size() - 1; 12 while (second < third) 13 { 14 if (nums[first] + nums[second] + nums[third] > target) 15 { 16 res = res < abs(target - (nums[first] + nums[second] + nums[third])) ? res : abs(target - (nums[first] + nums[second] + nums[third])); 17 rr = res < abs(target - (nums[first] + nums[second] + nums[third])) ? rr : (nums[first] + nums[second] + nums[third]); 18 third--; 19 continue; 20 } 21 if (nums[first] + nums[second] + nums[third] < target) 22 { 23 res = res < abs(target - (nums[first] + nums[second] + nums[third])) ? res : abs(target - (nums[first] + nums[second] + nums[third])); 24 rr = res < abs(target - (nums[first] + nums[second] + nums[third])) ? rr :(nums[first] + nums[second] + nums[third]); 25 second++; 26 continue; 27 } 28 if (nums[first] + nums[second] + nums[third] == target) 29 { 30 res = 0; 31 rr = target; 32 return rr; 33 } 34 } 35 } 36 return rr; 37 } 38 };