当前位置:网站首页>LeetCode每日一题:合并两个有序数组
LeetCode每日一题:合并两个有序数组
2022-07-05 17:17:00 【利刃Cc】
链接: 合并两个有序数组
这题有个要求:能不能使用O(m+n)的时间复杂度完成?
那当然是有的!
思路:用两个指针分别指向两个数组的尾部!这个很关键!
然后从后向前遍历。又题目可知,nums1的大小肯定是m+n的,且nums1的后半部分是空的,直接覆盖是没影响的。
所以就是将nums2中的元素与nums1中的比较,谁大就先放谁进去。
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++;
}
}
}
};
边栏推荐
- ICML 2022 | meta proposes a robust multi-objective Bayesian optimization method to effectively deal with input noise
- ICML 2022 | Meta提出鲁棒的多目标贝叶斯优化方法,有效应对输入噪声
- 华为云云原生容器综合竞争力,中国第一!
- Disabling and enabling inspections pycharm
- Cartoon: interesting [pirate] question
- Cartoon: how to multiply large integers? (integrated version)
- Winedt common shortcut key modify shortcut key latex compile button
- 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
- mysql如何使用JSON_EXTRACT()取json值
- MySQL之知识点(七)
猜你喜欢
Knowledge points of MySQL (6)
CVPR 2022 best student paper: single image estimation object pose estimation in 3D space
Example tutorial of SQL deduplication
統計php程序運行時間及設置PHP最長運行時間
服务器配置 jupyter环境
MySQL之知识点(七)
查看自己电脑连接过的WiFi密码
To solve the problem of "double click PDF file, pop up", please install Evernote program
c#图文混合,以二进制方式写入数据库
Compter le temps d'exécution du programme PHP et définir le temps d'exécution maximum de PHP
随机推荐
Troubleshooting - about clip not found Visual Studio
Cartoon: how to multiply large integers? (I) revised version
Count the running time of PHP program and set the maximum running time of PHP
What are the precautions for MySQL group by
MySQL之知识点(七)
mysql5.6解析JSON字符串方式(支持复杂的嵌套格式)
Example tutorial of SQL deduplication
一文了解Go语言中的函数与方法的用法
Knowing that his daughter was molested, the 35 year old man beat the other party to minor injury level 2, and the court decided not to sue
MySql 查询符合条件的最新数据行
ICML 2022 | meta proposes a robust multi-objective Bayesian optimization method to effectively deal with input noise
深入理解Redis内存淘汰策略
Disabling and enabling inspections pycharm
十个顶级自动化和编排工具
mongodb(快速上手)(一)
C (WinForm) the current thread is not in a single threaded unit, so ActiveX controls cannot be instantiated
33: Chapter 3: develop pass service: 16: use redis to cache user information; (to reduce the pressure on the database)
外盘黄金哪个平台正规安全,怎么辨别?
独立开发,不失为程序员的一条出路
力扣解法汇总729-我的日程安排表 I