leetcode -- Merge Sorted Array -- 简单重点

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

因为这里要求in place 修改nums1.所以不要新申请一个list。小trick就是two pointers 从list末尾开始scan。最后要注意n > m的时候,还要把剩余的nums2加到nums1中
http://chaoren.is-programmer.com/posts/42844.html

class Solution(object):
    def merge(self, nums1, m, nums2, n):
        """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead. """
        i,j,k = m - 1, n - 1, m + n - 1

        while i >= 0 and j >= 0:

            if nums1[i] > nums2[j]:
                nums1[k] = nums1[i]
                i -= 1
            else:
                nums1[k] = nums2[j]
                j -= 1
            k -= 1

        while j >= 0:
            nums1[k] = nums2[j]
            j -= 1
            k -= 1

你可能感兴趣的:(LeetCode)