当前位置:网站首页>leetcode16最接近的三数之和 (排序+ 双指针)
leetcode16最接近的三数之和 (排序+ 双指针)
2022-08-03 12:29:00 【_刘小雨】
作者简介:C/C++ 、Golang 领域耕耘者,创作者
个人主页:作者主页
活动地址:CSDN21天学习挑战赛
如果感觉博主的文章还不错的话,还请关注 、点赞 、收藏🧡三连支持一下博主哦~~~
题目描述
给你一个长度为 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
🧡 算法分析
此题用到了排序+ 双指针的思想
具体算法步骤为:
- 直接排序整个数组,然后从头开始遍历每个数,此时第一个数已经确定
- 用双指针l,r分别从左边
l = i + 1
和右边n - 1
往中间靠拢,找到sum = nums[i] + nums[l] + nums[r]
所有情况中最接近target
的sum
,更新re
- 在双指针移动的过程中,三数之和假设为sum
- 若sum > target,则r往左走,使sum变小,更接近target
- 若sum < target,则l往右走,使sum变大,更接近target
- 若sum == target,则表示找到了与num[i]搭配的组合num[l]和num[r],直接返回
代码实现
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
pair<int, int> re(INT_MAX, INT_MAX);
for(int i = 0; i< nums.size(); i++)
{
for(int j = i + 1, k = nums.size() - 1; j < k; j++)
{
while(k - 1 > j && nums[i] + nums[j] + nums[k - 1] >= target) k --;
int s = nums[i] + nums[j] + nums[k];
re = min(re, make_pair(abs(s - target), s)); // re中存取的是 差值 ,三数之和
if( k - 1 > j)
{
s = nums[i] + nums[j] + nums[k - 1]; // 找到前面一个
re = min(re, make_pair(abs(target - s), s));
}
}
}
return re.second;
}
};
执行结果:
时间复杂度分析
其中遍历了两种循环, 时间复杂度为O(n2)
如果觉得对你有帮助的话:
点赞,你的认可是我创作的动力!
🧡 收藏,你的青睐是我努力的方向!
️ 评论,你的意见是我进步的财富!
边栏推荐
- From the physical level of the device to the circuit level
- 特征工程学习笔记
- R language ggplot2 visualization: use the patchwork bag plot_layout function will be more visual image together, ncol parameter specifies the number of rows, specify byrow parameters configuration dia
- 可重入锁详解(什么是可重入)
- In order to counteract the drop in sales and explore the low-end market, Weilai's new brand products are priced as low as 100,000?
- 查看GCC版本_qt版本
- 自律成就自己
- R语言ggplot2可视化:使用patchwork包的plot_layout函数将多个可视化图像组合起来,ncol参数指定行的个数、byrow参数指定按照行顺序排布图
- 什么是分布式锁?几种分布式锁分别是怎么实现的?
- pandas连接oracle数据库并拉取表中数据到dataframe中、筛选当前时间(sysdate)到一天之前的所有数据(筛选一天范围数据)
猜你喜欢
随机推荐
Grafana 高可用部署最佳实践
随机森林项目实战---气温预测
The Yangtze river commercial Banks to the interview
无监督学习KMeans学习笔记和实例
期货公司开户关注的关键点
别再用if-else了,分享一下我使用“策略模式”的项目经验...
[数据仓库]分层概念,ODS,DM,DWD,DWS,DIM的概念「建议收藏」
From the physical level of the device to the circuit level
特征降维学习笔记(pca和lda)(1)
信创建设看广州|海泰方圆亮相2022 信创生态融合发展论坛
【云原生 · Kubernetes】部署Kubernetes集群
php microtime 封装工具类,计算接口运行时间(打断点)
Oracle is installed (system disk) and transferred from the system disk to the data disk
AMS simulation
4500 words sum up, a software test engineer need to master the skill books
Secure Custom Web Application Login
word标尺有哪些作用
Yahoo! Answers-数据集
Image fusion SDDGAN article learning
pytorch+tensorboard使用方法