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

边栏推荐
- Ant financial's sudden wealth has not yet begun, but the myth of zoom continues!
- 漫画:有趣的【海盗】问题
- Disabling and enabling inspections pycharm
- ICML 2022 | meta proposes a robust multi-objective Bayesian optimization method to effectively deal with input noise
- Cartoon: looking for the k-th element of an unordered array (Revised)
- Accuracy of BigDecimal Division
- 漏洞复现----48、Airflow dag中的命令注入(CVE-2020-11978)
- Cartoon: how to multiply large integers? (next)
- Database design in multi tenant mode
- 基于51单片机的电子时钟设计
猜你喜欢

北京内推 | 微软亚洲研究院机器学习组招聘NLP/语音合成等方向全职研究员
MySql 查询符合条件的最新数据行

查看自己电脑连接过的WiFi密码

ICML 2022 | Meta提出魯棒的多目標貝葉斯優化方法,有效應對輸入噪聲

7. Scala class

网络威胁分析师应该具备的十种能力

MySQL之知识点(六)

Machine learning 02: model evaluation

提高应用程序性能的7个DevOps实践

Compter le temps d'exécution du programme PHP et définir le temps d'exécution maximum de PHP
随机推荐
Summary of optimization scheme for implementing delay queue based on redis
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
网络威胁分析师应该具备的十种能力
Sentinel-流量防卫兵
得知女儿被猥亵,35岁男子将对方打至轻伤二级,法院作出不起诉决定
SQL Server(2)
flask接口响应中的中文乱码(unicode)处理
这个17岁的黑客天才,破解了第一代iPhone!
C#(Winform) 当前线程不在单线程单元中,因此无法实例化 ActiveX 控件
C#实现水晶报表绑定数据并实现打印3-二维码条形码
Cartoon: interesting [pirate] question
Cartoon: looking for the best time to buy and sell stocks
leetcode每日一题:字符串中的第一个唯一字符
33:第三章:开发通行证服务:16:使用Redis缓存用户信息;(以减轻数据库的压力)
查看自己电脑连接过的WiFi密码
求解为啥all(())是True, 而any(())是FALSE?
ICML 2022 | Meta propose une méthode robuste d'optimisation bayésienne Multi - objectifs pour faire face efficacement au bruit d'entrée
2022年信息系统管理工程师考试大纲
关于mysql中的json解析函数JSON_EXTRACT
This 17-year-old hacker genius cracked the first generation iPhone!