题目
思路
从后向前不断插入新值。
代码
class Solution:
"""
@param: A: sorted integer array A which has m elements, but size of A is m+n
@param: m: An integer
@param: B: sorted integer array B which has n elements
@param: n: An integer
@return: nothing
"""
def mergeSortedArray(self, A, m, B, n):
# write your code here
lastIndex = m + n - 1
i = m - 1; j = n - 1
while i >= 0 and j >= 0:
if A[i] > B[j]:
A[lastIndex] = A[i]
i -= 1
else:
A[lastIndex] = B[j]
j -= 1
lastIndex -= 1
while i >= 0:
A[lastIndex] = A[i]
i -= 1
lastIndex -= 1
while j >= 0:
A[lastIndex] = B[j]
j -= 1
lastIndex -= 1