当前位置:网站首页>Leetcode daily question: merge two ordered arrays
Leetcode daily question: merge two ordered arrays
2022-07-05 17:48:00 【Sharp blade CC】
link : Merge two ordered arrays
This question has a requirement : Can I use O(m+n) The time complexity of ?
Of course there are !
Ideas : Point to the tail of two arrays with two pointers ! This is the key !
Then traverse from back to front . You can know the title ,nums1 It must be the size of m+n Of , And nums1 The second half of the is empty , Direct coverage has no effect .
So it's going to be nums2 Elements in and nums1 The comparison in , Let whoever is old go in first .
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int p1=m-1,p2=n-1;
int i=1;
while(p1>=0||p2>=0)
{
if(p1<0)
{
nums1[m+n-i]=nums2[p2];
p2--;
i++;
}
else if(p2<0)
{
break;
}
else if(nums1[p1]<=nums2[p2])
{
nums1[m+n-i]=nums2[p2];
i++;
p2--;
}
else
{
nums1[m+n-i]=nums1[p1];
p1--;
i++;
}
}
}
};
边栏推荐
猜你喜欢
Database design in multi tenant mode
基于YOLOv3的口罩佩戴检测
flask接口响应中的中文乱码(unicode)处理
Why is all (()) true and any (()) false?
解决“双击pdf文件,弹出”请安装evernote程序
ICML 2022 | meta proposes a robust multi-objective Bayesian optimization method to effectively deal with input noise
Winedt common shortcut key modify shortcut key latex compile button
ICML 2022 | Meta提出魯棒的多目標貝葉斯優化方法,有效應對輸入噪聲
CVPR 2022最佳学生论文:单张图像估计物体在3D空间中的位姿估计
Count the running time of PHP program and set the maximum running time of PHP
随机推荐
Ordinary programmers look at the code, and top programmers look at the trend
服务器配置 jupyter环境
力扣解法汇总729-我的日程安排表 I
论文阅读_中文NLP_LTP
To solve the problem of "double click PDF file, pop up", please install Evernote program
Redis+caffeine two-level cache enables smooth access speed
Design of electronic clock based on 51 single chip microcomputer
Flow characteristics of kitchen knife, ant sword, ice scorpion and Godzilla
漫画:有趣的【海盗】问题
漫画:寻找无序数组的第k大元素(修订版)
漫画:有趣的海盗问题 (完整版)
EPM相关
独立开发,不失为程序员的一条出路
Mysql5.6 parsing JSON strings (supporting complex nested formats)
较文心损失一点点性能提升很多
rsync
The comprehensive competitiveness of Huawei cloud native containers ranks first in China!
BigDecimal除法的精度问题
Interpretation: how to deal with the current security problems faced by the Internet of things?
普通程序员看代码,顶级程序员看趋势