题目:
合并两个排序的整数数组A和B变成一个新的数组。
样例
给出A = [1, 2, 3, empty, empty] B = [4,5]
合并之后A将变成[1,2,3,4,5]
注意
你可以假设A具有足够的空间(A数组的大小大于或等于m+n)去添加B中的元素。
解题:
这里给的是两个数组,上题给的是ArrayList格式,比较好处理,重新定义一个长度m+n的数组,但是A的数组长度是m+n,可以从后面将元素插入的A数组中
class Solution {
/**
* @param A: sorted integer array A which has m elements,
* but size of A is m+n
* @param B: sorted integer array B which has n elements
* @return: void
*/
public void mergeSortedArray(int[] A, int m, int[] B, int n) {
// write your code here
int k = m + n -1;
m--;
n--;
while(m>=0 && n>=0){
if(A[m] >= B[n]){
A[k--] = A[m--];
}else{
A[k--] = B[n--];
}
}
while(n>=0){
A[k--] = B[n--];
} } }
也可以这样写
class Solution {
/**
* @param A: sorted integer array A which has m elements,
* but size of A is m+n
* @param B: sorted integer array B which has n elements
* @return: void
*/
public void mergeSortedArray(int[] A, int m, int[] B, int n) {
// write your code here
int k = m + n -1;
m--;
n--;
while(k>=0){
if(n<0 || (m>=0 && A[m] >= B[n])){
A[k--] = A[m--];
}else{
A[k--] = B[n--];
}
}
} }
Python程序:
class Solution:
"""
@param A: sorted integer array A which has m elements,
but size of A is m+n
@param B: sorted integer array B which has n elements
@return: void
"""
def mergeSortedArray(self, A, m, B, n):
# write your code here
for i in range(n):
A[m+i] = B[i]
A.sort()
return A
总耗时: 233 ms