当前位置:网站首页>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)
如果觉得对你有帮助的话:
点赞,你的认可是我创作的动力!
🧡 收藏,你的青睐是我努力的方向!
️ 评论,你的意见是我进步的财富!
边栏推荐
- GameFi 行业下滑但未出局| June Report
- Filebeat 如何保持文件状态?
- 易观分析:2022年Q2中国网络零售B2C市场交易规模达23444.7亿元
- 通过点击CheckBox实现背景变换小案例
- 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
- Jmeter使用
- php microtime encapsulates the tool class, calculates the running time of the interface (breakpoint)
- 从器件物理级提升到电路级
- An工具介绍之骨骼工具
- An工具介绍之钢笔工具、铅笔工具与画笔工具
猜你喜欢
随机推荐
流式编程使用场景
An introduction to the skeleton tool
self-discipline
ECCV 2022|通往数据高效的Transformer目标检测器
Feature Engineering Study Notes
Blog records life
An动画基础之元件的图形动画与按钮动画
【Verilog】HDLBits题解——Verification: Reading Simulations
数据库基础知识一(MySQL)[通俗易懂]
pandas连接oracle数据库并拉取表中数据到dataframe中、筛选当前时间(sysdate)到一天之前的所有数据(筛选一天范围数据)
博客记录生活
【Verilog】HDLBits题解——Verification: Writing Testbenches
安防监控必备的基础知识「建议收藏」
基于php旅游网站管理系统获取(php毕业设计)
YOLOv5训练数据提示No labels found、with_suffix使用、yolov5训练时出现WARNING: Ignoring corrupted image and/or label
An工具介绍之骨骼工具
[数据仓库]分层概念,ODS,DM,DWD,DWS,DIM的概念「建议收藏」
Secure Custom Web Application Login
(通过页面)阿里云云效上传jar
新评论接口——京东评论接口








