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 (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m andn respectively.
Analysis:Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m andn respectively.
The obvious way is to insert B's entries into A after each comparison, and shift all the rest of A to right. Repeating this until we reach the end of B. I bet you'll get TLE.
The way to improve is considering about avoid these shifts. As the A[m+1 : m+n] is empty, we could start from the large values and works backwards. See the following implementation. The time complexity is O(m+n) and no extra space is needed.
Code:
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
if (n==0) return;
if (m==0) {
for (int i=0; i<n; i++)
A[i]=B[i];
return;
}
int curA=m; int curB=n;
while(curB>0 && curA>0) {
if (A[curA-1]>=B[curB-1]) {
A[curA+curB-1]=A[curA-1];
curA--;
}
else {
A[curA+curB-1]=B[curB-1];
curB--;
}
}
if (curB>0)
for (int i=0; i<curB; i++)
A[i]=B[i];
if (curA>0)
return;
}
};
No comments:
Post a Comment