这题开始的思路时错的,后来看了网上的总结
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 and n respectively.
分析: 这题的特点是最后的数据都保存在数组A 中。 刚开始我想从前往后复制,是错的。
这和 merge two sorted list 不一样,如果最好数据都保存在a 中,a还没检测到的数据可能会被覆盖。
所以要从后往前复制。
写完代码,一些特殊情况都可以归并了
class Solution:
# @param A a list of integers
# @param m an integer, length of A
# @param B a list of integers
# @param n an integer, length of B
# @return nothing
def merge(self, A, m, B, n):
allcur,acur,bcur = m+n-1,m-1,n-1
for ind in range(m+n):
if acur==-1:
for indd in range(bcur+1):
A[indd] = B[indd]
break;
if bcur==-1:
break;
if A[acur]>=B[bcur]:
A[allcur] = A[acur]
acur -= 1
else:
A[allcur] = B[bcur]
bcur -= 1
allcur -= 1
C++
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
int allcur=m+n-1, acur=m-1, bcur=n-1;
for(int i=1;i<=m+n;i++){
if(acur==-1){
for(int j=0;j<(bcur+1);j++){
A[j]=B[j];
}
break;
}
if(bcur==-1){
break;
}
A[allcur--] = A[acur]>=B[bcur] ? A[acur--]:B[bcur--];
}
}
};
作为C++ 新手, 这里有新的认识:
1. 对 cur += 1, cur -= 1. 可以使用 cur++ or cur--。 出现前面的语句,就可以看看是不是能转成后一个
2. C++ 里用了三目运算,一下子省了很多代码。 在非常简单的 if else 语句中,要学会用。 这个非常方便。