数组16

/*
题意:找出给定数组中包含三个元素,其和最接近目标值的和
分析:基于15的思路,在第二重利用双指针,如果sum=target,则直接返回答案,如果sum>target,则右指针左移,否则左指针右移
************
这里有一个精简代码的方法可以去记忆*
auto update = [&](int cur){。};	*
								*
								*
								*
*/
int threeSum(vector<int>& nums, int target) {
	int ans=1<<30;//minsum表示目前的结果与target的最小距离
	int n = nums.size();
	sort(nums.begin(), nums.end());
	auto update = [&](int cur) {
		if (abs(cur - target) < abs(ans - target)) {
			ans = cur;
		}
	};
	for (int a = 0; a < n; ++a) {
		if (a > 0 && nums[a] == nums[a - 1]) continue;
		int b = a + 1, c = n - 1;
		while (b < c) {
			int sum = nums[a] + nums[b] + nums[c];
			update(sum);
			if (sum == target) return sum;
			if (sum > target) {
				int c0 = c-1;
				while (b < c0&&nums[c0] == nums[c]) --c0;
				c = c0;
			}
			else {
				int b0 = b + 1;
				while (b0 < c&&nums[b0] == nums[b]) ++b0;
				b = b0;
			}

		}
	}
	return ans;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值