当前位置:网站首页>Leetcode (88) -- merge two ordered arrays
Leetcode (88) -- merge two ordered arrays
2022-06-28 14:30:00 【SmileGuy17】
Leetcode(88)—— Merge two ordered arrays
subject
Here are two buttons Non decreasing order Array of arranged integers nums1 and nums2, There are two other integers m and n , respectively nums1 and nums2 The number of elements in .
Would you please Merge nums2 To nums1 in , Make the merged array press Non decreasing order array .
Be careful : Final , The merged array should not be returned by the function , It's stored in an array nums1 in . In response to this situation ,nums1 The initial length of is m + n, The top m Elements represent the elements that should be merged , after n Elements are 0 , It should be ignored .nums2 The length of is n .
Example 1:
Input :nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output :[1,2,2,3,5,6]
explain : Need merger [1,2,3] and [2,5,6] .
The combined result is [1,2,2,3,5,6] , In which, bold italics indicates nums1 The elements in .
Example 2:
Input :nums1 = [1], m = 1, nums2 = [], n = 0
Output :[1]
explain : Need merger [1] and [] .
The combined result is [1] .
Example 3:
Input :nums1 = [0], m = 0, nums2 = [1], n = 1
Output :[1]
explain : The array to be merged is [] and [1] .
The combined result is [1] .
Be careful , because m = 0 , therefore nums1 No elements in .nums1 The only remaining 0 Just to ensure that the merged results can be successfully stored in nums1 in .
Tips :
- nums1.length == m + n
- nums2.length == n
- 0 0 0 <= m, n <= 200 200 200
- 1 1 1 <= m + n <= 200 200 200
- − 1 0 9 -10^9 −109 <= nums1[i], nums2[j] <= 1 0 9 10^9 109
Advanced : You can design and implement a time complexity of O ( m + n ) O(m + n) O(m+n) Does the algorithm solve this problem ?
Answer key
Method 1 : Sort after direct merge
Ideas
The most intuitive way is to put the array first nums 2 \textit{nums}_2 nums2 Put it in the array nums 1 \textit{nums}_1 nums1 Tail of , Then sort the entire array directly .
Code implementation
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
for (int i = 0; i != n; ++i) {
nums1[m + i] = nums2[i];
}
sort(nums1.begin(), nums1.end());
}
};
Complexity analysis
Time complexity : O ( ( m + n ) l o g ( m + n ) ) O((m+n)log(m+n)) O((m+n)log(m+n)). The length of the sorting sequence is m + n m+n m+n, Apply the time complexity of quick sorting , The average is O ( ( m + n ) log ( m + n ) ) O((m+n)\log(m+n)) O((m+n)log(m+n)).
Spatial complexity : O ( log ( m + n ) ) O(\log(m+n)) O(log(m+n)) The length of the sorting sequence is m + n m+n m+n, Because quick sort is used , Therefore, the space complexity of quick sorting can be applied , The average is O ( log ( m + n ) ) O(\log(m+n)) O(log(m+n)).
Method 2 : Double pointer + Auxiliary array
Ideas
Method 1 does not utilize arrays nums 1 \textit{nums}_1 nums1 And nums 2 \textit{nums}_2 nums2 The property that has been sorted . In order to take advantage of this property , We can use the double pointer method . This method treats the two arrays as queues , Take out the smaller number from the two array headers at a time and put it into the result . We set a pointer to each of the two arrays p 1 p_1 p1 And p 2 p_2 p2 As a pointer to the head of the queue . As shown in the animation below :
Code implementation
Leetcode Official explanation :
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int p1 = 0, p2 = 0;
int sorted[m + n];
int cur;
while (p1 < m || p2 < n) {
if (p1 == m) {
cur = nums2[p2++];
} else if (p2 == n) {
cur = nums1[p1++];
} else if (nums1[p1] < nums2[p2]) {
cur = nums1[p1++];
} else {
cur = nums2[p2++];
}
sorted[p1 + p2 - 1] = cur;
}
for (int i = 0; i != m + n; ++i) {
nums1[i] = sorted[i];
}
}
};
Complexity analysis
Time complexity : O ( m + n ) O(m+n) O(m+n). The movement of the pointer decreases monotonously , Move at most m + n m+n m+n Time , So the time complexity is zero O ( m + n ) O(m+n) O(m+n).
Spatial complexity : O ( m + n ) O(m+n) O(m+n). Need to establish a length of m + n m+n m+n The middle array of sorted \textit{sorted} sorted
Method 3 : Double reverse pointer
Ideas
Method 2 , The reason for using temporary variables , Because if you merge directly into an array nums 1 \textit{nums}_1 nums1 in , nums 1 \textit{nums}_1 nums1 Elements in may be covered before they are removed . So how to avoid coverage directly nums 1 \textit{nums}_1 nums1 And the elements in it ? Observation can be seen , nums 1 \textit{nums}_1 nums1 The second half of the is empty , Can be covered directly without affecting the results . So you can set the pointer to traverse from back to front , Take the larger of the two at a time and put it in nums 1 \textit{nums}_1 nums1 At the back of .
Strictly speaking , At any point in the traversal , nums 1 \textit{nums}_1 nums1 Array has m − p 1 − 1 m-p_1-1 m−p1−1 Elements are put into nums 1 \textit{nums}_1 nums1 The second half of the , nums 2 \textit{nums}_2 nums2 Array has n − p 2 − 1 n-p_2-1 n−p2−1 Elements are put into nums 1 \textit{nums}_1 nums1 The second half of the , And in the pointer p 1 p_1 p1 Behind , nums 1 \textit{nums}_1 nums1 Array has m + n − p 1 − 1 m+n-p_1-1 m+n−p1−1 A place . because
m + n − p 1 − 1 ≥ m − p 1 − 1 + n − p 2 − 1 m+n-p_1-1\geq m-p_1-1+n-p_2-1 m+n−p1−1≥m−p1−1+n−p2−1
Equivalent to
p 2 ≥ − 1 p_2\geq -1 p2≥−1
Forever , therefore p 1 p_1 p1 The back position is always enough to hold the inserted element , Will not produce p 1 p_1 p1 The case where the elements of are covered .
Code implementation
Leetcode Official explanation :
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int pos = m-- + n-- - 1;
while (m >= 0 && n >= 0)
nums1[pos--] = nums1[m] > nums2[n]? nums1[m--]: nums2[n--];
while (n >= 0)
nums1[pos--] = nums2[n--];
}
};
My own :
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
if(n == 0) return;
while(true){
if(m <= 0){
while(n){
nums1[n+m-1] = nums2[n-1];
n--;
}
}
if(n <= 0) return;
if(nums1[m-1] >= nums2[n-1]){
nums1[n+m-1] = nums1[m-1];
m--;
}else{
nums1[n+m-1] = nums2[n-1];
n--;
}
}
}
};
Complexity analysis
Time complexity : O ( m + n ) O(m+n) O(m+n). The movement of the pointer decreases monotonously , Move at most m + n m+n m+n Time , So the time complexity is zero O ( m + n ) O(m+n) O(m+n).
Spatial complexity : O ( 1 ) O(1) O(1). Directly to arrays nums 1 \textit{nums}_1 nums1
边栏推荐
- Adding virtual environments to the Jupiter notebook
- Double buffer drawing
- 华泰证券app 怎么办理开户最安全
- Flutter series: offstage in flutter
- 接雨水系列问题
- Operation and maintenance thinking | do you know the relationship between CMDB and monitoring?
- Regular matching numbers, English and English symbols
- IonQ联合GE Research证实:量子计算在风险聚合上有巨大潜力
- 增额终身寿险有哪些产品可以买呢?
- 荐书丨《大脑通信员》:如果爱情只是化学反应,那还能相信爱情吗?
猜你喜欢
The time schedule for the soft test in the second half of 2022 has been determined!
Adding virtual environments to the Jupiter notebook
基于asp.net的文献检索系统
Research and Simulation of chaotic digital image encryption technology based on MATLAB
Practice of constructing ten billion relationship knowledge map based on Nebula graph
基于ASP的勤工俭学管理系统
美因基因港交所上市:市值43亿港元 IPO被市场忽略
如何设计数据可视化平台
Four methods of thread termination
IonQ联合GE Research证实:量子计算在风险聚合上有巨大潜力
随机推荐
Why can't Bert completely kill the BM25??
正则匹配数字,英文以及英文符号
Go array and slice, []byte to string[easy to understand]
Npoi export excel and download to client
Numbers that only appear once
智联招聘基于 Nebula Graph 的推荐实践分享
Native JS implements drag and drop of page elements
Connected to rainwater series problems
开源社邀您参加OpenInfra Days China 2022,议题征集进行中~
Four visualization tools are recommended to solve 99% of large screen visualization projects!
力扣解法汇总522-最长特殊序列 II
i++ , ++i
What are the consequences of opening an account with Huatai Securities? How to open an account is the safest
证券公司和银行哪个更安全 怎么办理开户最安全
Four methods of thread termination
配置文件加密(Jasypt的简单使用)
What is the progress of China open source with 7.55 million developers?
增额终身寿险有哪些产品可以买呢?
openGauss内核:SQL解析过程分析
G: maximum flow problem