Question: https://oj.leetcode.com/problems/merge-sorted-array/

Question Name: Merge Sorted Array

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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): lastA, lastB = m-1, n-1 # Travel A and B from right to left last2Write = m + n -1 # Write the integers from the rightmost # position to the leftmost position of A while lastA != -1 and lastB != -1: if A[lastA] >= B[lastB]: A[last2Write] = A[lastA] lastA -= 1 else: A[last2Write] = B[lastB] lastB -= 1 last2Write -= 1 # If A list has some remaining items to process, they are already in # their to-be position. No operation is needed. # Otherwise, if B list has some remaining items, copy them to the head # of A. if lastB != -1: A[:lastB+1] = B[:lastB+1] return |