当前位置:网站首页>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)
如果觉得对你有帮助的话:
点赞,你的认可是我创作的动力!
🧡 收藏,你的青睐是我努力的方向!
️ 评论,你的意见是我进步的财富!
边栏推荐
猜你喜欢
An工具介绍之钢笔工具、铅笔工具与画笔工具
An动画基础之散件动画原理与形状提示点
如何免费获得一个市全年的气象数据?降雨量气温湿度太阳辐射等等数据
图像融合SDDGAN文章学习
链游NFT元宇宙游戏系统开发技术方案及源码
一次内存泄露排查小结
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
Apache APISIX 2.15 版本发布,为插件增加更多灵活性
899. 有序队列
An动画基础之按钮动画与基础代码相结合
随机推荐
622. 设计循环队列
GameFi 行业下滑但未出局| June Report
为冲销量下探中低端市场,蔚来新品牌产品定价低至10万?
信创建设看广州|海泰方圆亮相2022 信创生态融合发展论坛
苹果发布 AI 生成模型 GAUDI,文字生成 3D 场景
基于php校园医院门诊管理系统获取(php毕业设计)
R语言拟合ARIMA模型并使用拟合模型进行预测推理、使用autoplot函数可视化ARIMA模型预测结果、可视化包含置信区间的预测结果
Unsupervised learning KMeans notes and examples
Nodejs 安装依赖cpnm时,install 出现Error: Cannot find module ‘fs/promises‘
Byte's favorite puzzle questions, how many do you know?
leetcode 11. 盛最多水的容器
类和对象(中下)
期货公司开户关注的关键点
Blog records life
An工具介绍之3D工具
数据库系统原理与应用教程(073)—— MySQL 练习题:操作题 131-140(十七):综合练习
shell编程之条件语句
随机森林项目实战---气温预测
浅谈低代码平台远程组件加载方案
The common problems in the futures account summary