class Solution {
public:
void merge(int A[], int m, int B[], int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<int> tmp(m+n,0);//O(m+n)的辅助空间
int loc1=0,loc2=0,loc3=0;
while(loc1<=m-1&&loc2<=n-1)
{
if(A[loc1]<B[loc2])
tmp[loc3++]=A[loc1++];
else//保证A[]中始终放小的
tmp[loc3++]=B[loc2++];
}
while(loc1<=m-1)//将A[]中剩下的插入tmp末尾
tmp[loc3++]=A[loc1++];
while(loc2<=n-1)//将B[]中剩下的插入tmp末尾
tmp[loc3++]=B[loc2++];
for(int i=0;i<m+n;i++)
A[i]=tmp[i];
}
};
【leetcode】Merge Sorted Array
最新推荐文章于 2024-07-21 20:23:11 发布
本文介绍了一种使用辅助空间优化数组合并操作的方法,通过引入临时数组来整合两个已排序数组,确保了操作的效率并减少了内存占用。

323

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



