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

边栏推荐
- 统计php程序运行时间及设置PHP最长运行时间
- Count the running time of PHP program and set the maximum running time of PHP
- mybash
- ICML 2022 | meta proposes a robust multi-objective Bayesian optimization method to effectively deal with input noise
- Knowledge points of MySQL (7)
- Cartoon: how to multiply large integers? (next)
- 服务器配置 jupyter环境
- Rider set the highlighted side of the selected word, remove the warning and suggest highlighting
- 漫画:寻找无序数组的第k大元素(修订版)
- 力扣解法汇总1200-最小绝对差
猜你喜欢

Six bad safety habits in the development of enterprise digitalization, each of which is very dangerous!

Kafaka technology lesson 1

mybash
Complete solution instance of Oracle shrink table space

哈趣K1和哈趣H1哪个性价比更高?谁更值得入手?

Knowledge points of MySQL (6)

十个顶级自动化和编排工具

ELK日志分析系统

Count the running time of PHP program and set the maximum running time of PHP

Ten top automation and orchestration tools
随机推荐
This 17-year-old hacker genius cracked the first generation iPhone!
毫无章法系列
Cmake tutorial step6 (add custom commands and generate files)
Please tell me why some tables can find data by writing SQL, but they can't be found in the data map, and the table structure can't be found
Cartoon: looking for the best time to buy and sell stocks
力扣解法汇总729-我的日程安排表 I
統計php程序運行時間及設置PHP最長運行時間
世界上最难的5种编程语言
证券网上开户安全吗?证券融资利率一般是多少?
解读:如何应对物联网目前面临的安全问题?
蚂蚁金服的暴富还未开始,Zoom的神话却仍在继续!
Cmake tutorial Step4 (installation and testing)
“12306” 的架构到底有多牛逼?
独立开发,不失为程序员的一条出路
如何修改mysql字段为自增长字段
Knowledge points of MySQL (7)
SQL Server(2)
Is it safe for China Galaxy Securities to open an account? How long can I buy stocks after opening an account
基于YOLOv3的口罩佩戴检测
Accuracy of BigDecimal Division