python实现leetcode之88. 合并两个有序数组

2021-09-17  本文已影响0人  深圳都这么冷

解题思路

反向的索引ridx先指向总数组的尾部
然后复制直到nums2复制完
如果nums1没有元素,直接复制nums2的即可
否则将大的复制过去并且ridx与被复制的元素同时减1

代码

88. 合并两个有序数组

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: None Do not return anything, modify nums1 in-place instead.
        """
        ridx = m + n - 1  # 反向的索引,先指向总数组的尾部
        m, n = m-1, n-1
        while n >= 0:  # nums2还有没有复制过来的元素
            if m < 0 or nums1[m] < nums2[n]:
                nums1[ridx] = nums2[n]
                n -= 1
            else:
                nums1[ridx] = nums1[m]
                m -= 1
            ridx -= 1
效果图
上一篇 下一篇

猜你喜欢

热点阅读