Array + two points leetcode.16 - 3Sum Closest
2024-09-01 15:22:37
题面
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.
给定数组,找出并返回最接近target的三个元素的和。可以假设,只有一个解。
样例
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题 3Sum中做过,三数加和为target的问题,采用了Two-Point逼近的方法。本题我们稍加改动就可以解决。
1. 数组排序,固定一个元素i,通过两点法去[i+1, size()-1]中搜索另外两个数字,先计算他们的和;
2. 若sum == target,直接返回;若不等,就需要判断sum与 我们给的初值res 那个更加接近target,即判断 abs(sum - target) 与 abs(res - target)的大小,对res进行更新,另外注意 l 和 r 的更新。
3. 返回res.
源码
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int len = nums.size();
if(len < )
return ;
//数组升序排序
sort(nums.begin(), nums.end());
int res = nums[]+nums[]+nums[];
for(int i=; i<len; i++)
{
if(i> && nums[i]==nums[i-])
i++;//避免i的重复,不必要
int l = i+, r = len-;
while(l < r)//两点法搜搜
{
int sum = nums[i] + nums[l] + nums[r];
if(sum == target)
return sum;
else if(sum > target)
{
if(abs(sum - target) < abs(res - target))
res = sum;
r--;
}
else
{
if(abs(sum - target) < abs(res - target))
res = sum;
l++;
}
}
}
return res;
}
};
最新文章
- Android之弹出/隐藏系统软键盘
- A - The Moronic Cowmpouter
- go gomail
- EChars学习-2
- Spring学习笔记之整合hibernate
- media type与media query
- hdu4435 charge-station(先建后拆+bfs)
- hdoj 2767 Proving Equivalences【求scc&;&;缩点】【求最少添加多少条边使这个图成为一个scc】
- hdu 4445 Crazy Tank (暴力枚举)
- [自制操作系统] 原子操作&核间中断&读写锁&PRWLock
- Android程序启动过程深入解析
- shiro的登陆认证(shiro项目中来的一)
- C语言二维数组作业
- 强制不使用“兼容性视图”的HTML代码
- Nodejs 安装 on centos7
- python dash 初探 --- k 线国内版
- what&#39;s the python之基本运算符及字符串、列表、元祖、集合、字典的内置方法
- NOIP2018濒死记
- 【转】Redis 总结精讲 看一篇成高手系统-4
- 纯CSS实现3D图像轮转