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

边栏推荐
- What are the precautions for MySQL group by
- Short the command line via jar manifest or via a classpath file and rerun
- 漫画:如何实现大整数相乘?(整合版)
- 33:第三章:开发通行证服务:16:使用Redis缓存用户信息;(以减轻数据库的压力)
- 一文了解MySQL事务隔离级别
- ClickHouse(03)ClickHouse怎么安装和部署
- mysql5.6解析JSON字符串方式(支持复杂的嵌套格式)
- Tips for extracting JSON fields from MySQL
- 华为云云原生容器综合竞争力,中国第一!
- Independent development is a way out for programmers
猜你喜欢

Compter le temps d'exécution du programme PHP et définir le temps d'exécution maximum de PHP

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

thinkphp3.2.3

解决“双击pdf文件,弹出”请安装evernote程序

Kafaka技术第一课
Database design in multi tenant mode

Machine learning 01: Introduction

Knowledge points of MySQL (7)

IDEA 项目启动报错 Shorten the command line via JAR manifest or via a classpath file and rerun.
MySql 查询符合条件的最新数据行
随机推荐
Count the running time of PHP program and set the maximum running time of PHP
Independent development is a way out for programmers
北京内推 | 微软亚洲研究院机器学习组招聘NLP/语音合成等方向全职研究员
使用QT设计师界面类创建2个界面,通过按键从界面1切换到界面2
Clickhouse (03) how to install and deploy Clickhouse
ICML 2022 | meta proposes a robust multi-objective Bayesian optimization method to effectively deal with input noise
About JSON parsing function JSON in MySQL_ EXTRACT
Database design in multi tenant mode
Q2 encryption market investment and financing report in 2022: gamefi becomes an investment keyword
Oracle缩表空间的完整解决实例
thinkphp3.2.3
Check the WiFi password connected to your computer
SQL删除重复数据的实例教程
ICML 2022 | Meta propose une méthode robuste d'optimisation bayésienne Multi - objectifs pour faire face efficacement au bruit d'entrée
33:第三章:开发通行证服务:16:使用Redis缓存用户信息;(以减轻数据库的压力)
2022年信息系统管理工程师考试大纲
Tita performance treasure: how to prepare for the mid year examination?
MySQL之知识点(六)
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
Flask solves the problem of CORS err