题目
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
思路一
将 B 中的每一元素都插入排序到 A 数组中。
先将 A 数组长度加一,再从后往前查找要插入的位置。
时间复杂度 O(MN)
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(m==0)
{
for(int i=0;i<n;i++)
A[i] = B[i];
return ;
}
int len = m;
for(int i=0;i<n;i++)
{
len = len+1;
int ind = len-1;
while(ind>0 && A[ind-1]>B[i])
{
A[ind] = A[ind-1];
ind--;
}
A[ind] = B[i];
}
return ;
}
};
思路二
这里时间复杂度是 O(M+N),从后往前比较A数组和B数组的每个值大小,并插入到合适的位置。
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(m==0)
{
for(int i=0;i<n;i++)
A[i] = B[i];
return ;
}
while( n )
{
if(m<=0 || A[m-1]<B[n-1])
{
A[m+n-1] = B[n-1];
n--;
}
else
{
A[m+n-1] = A[m-1];
m--;
}
}
}
};
类似的代码
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
int pos = m+n-1;
int a = m-1;
int b = n-1;
while(a>=0 && b>=0)
A[pos--] = A[a]>B[b] ? A[a--]:B[b--];
while(b>=0)
A[pos--] = B[b--];
}
};
本文详细介绍了如何使用C++合并两个已排序数组的方法,包括两种思路:一种是逐个插入排序,时间复杂度为O(MN);另一种是从后往前比较并插入,时间复杂度为O(M+N)。
326

被折叠的 条评论
为什么被折叠?



