Tuesday, August 18, 2015

Leetcode 88. Merge Sorted Array

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

Put numbers from back of nums1 (here is A), just like the empty list to merge two lists. Because the space is enough, there will not be any trouble.

There are two cases:
1. i = 0 first. For this case, B's remaining elements still need to be put into A.
2. j = 0 first. Because A is sorted, the remaining part of A does not need any operation.

Solution:
# T:O(n) S:O(1)
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):
        last, i, j = m + n - 1, m - 1, n - 1
        
        while i >= 0 and j >= 0:
            if A[i] > B[j]:
                A[last] = A[i]
                last, i = last - 1, i - 1
            else:
                A[last] = B[j]
                last, j = last - 1, j - 1
        
        while j >= 0:
                A[last] = B[j]
                last, j = last - 1, j - 1
Run Time: 48 ms

No comments:

Post a Comment