Merge Sorted Array in python

问题链接

https://leetcode.com/explore/interview/card/top-interview-questions-easy/96/sorting-and-searching/587/

解题思路

从nums1的m+n-1开始倒填

代码

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.
        """
        if n == 0:
            return
        
        p = m + n -1
        idx1 = m - 1
        idx2 = n - 1
        while idx1 >= 0 and idx2 >= 0:
            if nums1[idx1] >= nums2[idx2]:
                nums1[p] = nums1[idx1]
                idx1 -= 1
                p -= 1
            else:
                nums1[p] = nums2[idx2]
                idx2 -= 1
                p -= 1
        
        remindidx= idx1 if idx1 >= 0 else idx2
        remindnums = nums1 if idx1 >= 0 else nums2
        for i in range(remindidx, -1, -1):
            nums1[p] = remindnums[i]
            p -= 1

你可能感兴趣的:(Merge Sorted Array in python)