16. 最接近的三数之和(C++)---(排序+双指针)解题

题目详情
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

示例:
输入:
nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
 

提示:

  • 3 <= nums.length <= 10^3
  • -10^3 <= nums[i] <= 10^3
  • -10^4 <= target <= 10^4


——题目难度:中等


 


 


这道题和15. 三数之和的解法其实差不了很多,只是在second和third的移动上有些差别。但是解题时保证不重复的核心还是先得对nums进行排序。

 

 

设delta = nums[first] + nums[second] + nums[third] - target,当delta = 0,当然就是和target最接近 直接返回即可;
当delta > 0,说明nums[first] + nums[second] + nums[third] 大于 target,那么就需要缩小 三数之和 ,因为second只能往右移动,这样会导致 三数之和 越来越大,所以只能让third往左移动;
当delta < 0,说明nums[first] + nums[second] + nums[third] 小于 target,那么就需要增大 三数之和 ,因为third只能往左移动,这样会导致 三数之和 越来越小,所以只能让second往右移动。

 




-代码如下

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
		sort(nums.begin(), nums.end());
		int n = nums.size();
		int ansSum = nums[0] + nums[1] + nums[2];
		
		for (int first = 0; first < n - 2; first++)
		{
			if (first > 0 && nums[first] == nums[first-1])
				continue;
				
			int second = first + 1;
			int third = n - 1;
			while (second < third) {
				int tmpSum = nums[first] + nums[second] + nums[third];
				if (abs(ansSum - target) > abs(tmpSum - target)) {
					ansSum = tmpSum;
				}
				
				//delta = nums[first] + nums[second] + nums[third] - target
				int delta = tmpSum - target; 
				if (delta == 0) {
					return ansSum;
				}
				else if (delta > 0) { //nums[first] + nums[second] + nums[third] > target
					third--;
				}
				else { //nums[first] + nums[second] + nums[third] < target
					second++;
				}
			}
		}
			
		return ansSum;	
    }
};


结果(有点慢呀...)



 


 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

重剑DS

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值