当前位置:网站首页>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++;
}
}
}
};
边栏推荐
- Compter le temps d'exécution du programme PHP et définir le temps d'exécution maximum de PHP
- 7. Scala class
- Short the command line via jar manifest or via a classpath file and rerun
- 2022年信息系统管理工程师考试大纲
- Oracle缩表空间的完整解决实例
- Tita 绩效宝:如何为年中考核做准备?
- MySQL之知识点(七)
- Machine learning 01: Introduction
- mysql5.6解析JSON字符串方式(支持复杂的嵌套格式)
- 一文了解MySQL事务隔离级别
猜你喜欢
随机推荐
论文阅读_中文NLP_LTP
QT控制台打印输出
ICML 2022 | Meta propose une méthode robuste d'optimisation bayésienne Multi - objectifs pour faire face efficacement au bruit d'entrée
Customize the theme of matrix (I) night mode
Mysql5.6 parsing JSON strings (supporting complex nested formats)
Cartoon: how to multiply large integers? (I) revised version
leetcode每日一练:旋转数组
Alpha conversion from gamma space to linner space under URP (II) -- multi alpha map superposition
排错-关于clion not found visual studio 的问题
Independent development is a way out for programmers
证券网上开户安全吗?证券融资利率一般是多少?
Tips for extracting JSON fields from MySQL
世界上最难的5种编程语言
thinkphp3.2.3
Seven Devops practices to improve application performance
Use QT designer interface class to create two interfaces, and switch from interface 1 to interface 2 by pressing the key
这个17岁的黑客天才,破解了第一代iPhone!
Knowledge points of MySQL (7)
得知女儿被猥亵,35岁男子将对方打至轻伤二级,法院作出不起诉决定
ICML 2022 | Meta提出魯棒的多目標貝葉斯優化方法,有效應對輸入噪聲