当前位置:网站首页>leetcode16 Sum of the closest three numbers (sort + double pointer)
leetcode16 Sum of the closest three numbers (sort + double pointer)
2022-08-03 13:03:00 【_Liu Xiaoyu】
作者简介: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
🧡 算法分析
Sorting is used in this question+ 双指针的思想
具体算法步骤为:
- Sort the entire array directly,Then iterate over each number from the beginning,At this point the first number has been determined
- 用双指针l,r分别从左边
l = i + 1和右边n - 1往中间靠拢,找到sum = nums[i] + nums[l] + nums[r]closest of alltarget的sum,更新re - During the movement of the double pointer,The sum of the three numbers is assumed to be sum
- 若sum > target,则r往左走,使sum变小,更接近target
- 若sum < target,则l往右走,使sum变大,更接近target
- 若sum == target,Indicates that and is foundnum[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]; // find the previous one
re = min(re, make_pair(abs(target - s), s));
}
}
}
return re.second;
}
};
执行结果:
时间复杂度分析
Two kinds of loops are traversed, 时间复杂度为O(n2)
如果觉得对你有帮助的话:
点赞,你的认可是我创作的动力!
🧡 收藏,你的青睐是我努力的方向!
️ 评论,你的意见是我进步的财富!
边栏推荐
- 项目概述、推送和存储平台准备
- Apache APISIX 2.15 版本发布,为插件增加更多灵活性
- 622. 设计循环队列
- An工具介绍之形状工具及渐变变形工具
- An工具介绍之钢笔工具、铅笔工具与画笔工具
- 安防监控必备的基础知识「建议收藏」
- An动画优化之传统引导层动画
- 第十五章 源代码文件 REST API 简介
- Station B responded that "HR said that core users are all Loser": the interviewer was persuaded to quit at the end of last year and will learn lessons to strengthen management
- 海外代购系统/代购网站怎么搭建——源码解析
猜你喜欢
随机推荐
Blog records life
Last blog for July
word标尺有哪些作用
nacos应用
AMS simulation
图像融合GAN-FM学习笔记
从器件物理级提升到电路级
Grafana 高可用部署最佳实践
Oracle is installed (system disk) and transferred from the system disk to the data disk
Filebeat 如何保持文件状态?
一次内存泄露排查小结
R语言使用ggpubr包的ggtexttable函数可视化表格数据(直接绘制表格图或者在图像中添加表格数据)、使用tab_add_vline函数自定义表格中竖线(垂直线)的线条类型以及线条粗细
How to build an overseas purchasing system/purchasing website - source code analysis
技术分享 | 接口自动化测试如何搞定 json 响应断言?
nacos app
pandas连接oracle数据库并拉取表中数据到dataframe中、生成当前时间的时间戳数据、格式化为指定的格式(“%Y-%m-%d-%H-%M-%S“)并添加到csv文件名称中
pandas连接oracle数据库并拉取表中数据到dataframe中、筛选当前时间(sysdate)到一天之前的所有数据(筛选一天范围数据)
shell编程之条件语句
业界新标杆!阿里开源自研高并发编程核心笔记(2022最新版)
随机森林项目实战---气温预测









