当前位置:网站首页>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 propose une méthode robuste d'optimisation bayésienne Multi - objectifs pour faire face efficacement au bruit d'entrée
- 统计php程序运行时间及设置PHP最长运行时间
- leetcode每日一练:旋转数组
- 解决“双击pdf文件,弹出”请安装evernote程序
- 企业数字化发展中的六个安全陋习,每一个都很危险!
- 北京内推 | 微软亚洲研究院机器学习组招聘NLP/语音合成等方向全职研究员
- 机器学习01:绪论
- 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: a bloody case caused by a math problem
- mysql5.6解析JSON字符串方式(支持复杂的嵌套格式)
猜你喜欢
Complete solution instance of Oracle shrink table space
ICML 2022 | meta proposes a robust multi-objective Bayesian optimization method to effectively deal with input noise
33: Chapter 3: develop pass service: 16: use redis to cache user information; (to reduce the pressure on the database)
Kafaka technology lesson 1
C # mixed graphics and text, written to the database in binary mode
SQL删除重复数据的实例教程
基于Redis实现延时队列的优化方案小结
Alpha conversion from gamma space to linner space under URP (II) -- multi alpha map superposition
Database design in multi tenant mode
每日一练:关于日期的一系列
随机推荐
Ordinary programmers look at the code, and top programmers look at the trend
The five most difficult programming languages in the world
Beijing internal promotion | the machine learning group of Microsoft Research Asia recruits full-time researchers in nlp/ speech synthesis and other directions
企业数字化发展中的六个安全陋习,每一个都很危险!
Cartoon: a bloody case caused by a math problem
Tita performance treasure: how to prepare for the mid year examination?
Complete solution instance of Oracle shrink table space
Kafaka technology lesson 1
Flask solves the problem of CORS err
BigDecimal除法的精度问题
7 pratiques devops pour améliorer la performance des applications
Flow characteristics of kitchen knife, ant sword, ice scorpion and Godzilla
ClickHouse(03)ClickHouse怎么安装和部署
Matery主题自定义(一)黑夜模式
力扣解法汇总1200-最小绝对差
Clickhouse (03) how to install and deploy Clickhouse
Check the WiFi password connected to your computer
CVPR 2022最佳学生论文:单张图像估计物体在3D空间中的位姿估计
提高應用程序性能的7個DevOps實踐
In depth understanding of redis memory obsolescence strategy