当前位置:网站首页>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++;
}
}
}
};

边栏推荐
猜你喜欢

c#图文混合,以二进制方式写入数据库
Redis+caffeine two-level cache enables smooth access speed

leetcode每日一题:字符串中的第一个唯一字符

leetcode每日一练:旋转数组

flask接口响应中的中文乱码(unicode)处理

Kafaka技术第一课

ICML 2022 | Meta提出鲁棒的多目标贝叶斯优化方法,有效应对输入噪声

VBA drives SAP GUI to realize office automation (II): judge whether elements exist

CVPR 2022 best student paper: single image estimation object pose estimation in 3D space

每日一练:关于日期的一系列
随机推荐
WebApp开发-Google官方教程
Sentinel flow guard
漏洞复现----48、Airflow dag中的命令注入(CVE-2020-11978)
Size_t 是无符号的
Database design in multi tenant mode
Clickhouse (03) how to install and deploy Clickhouse
证券网上开户安全吗?证券融资利率一般是多少?
MySQL之知识点(七)
漫画:寻找无序数组的第k大元素(修订版)
QT控制台打印输出
一口气读懂 IT发展史
神经网络自我认知模型
7 pratiques devops pour améliorer la performance des applications
Read the history of it development in one breath
LeetCode 练习——206. 反转链表
基于YOLOv3的口罩佩戴检测
漫画:有趣的【海盗】问题
Cmake tutorial Step3 (requirements for adding libraries)
Cartoon: how to multiply large integers? (next)
Cartoon: looking for the best time to buy and sell stocks