美文网首页
《剑指Offer》合并有序列表 Python实现

《剑指Offer》合并有序列表 Python实现

作者: 4v3r9 | 来源:发表于2019-01-10 18:43 被阅读5次

1 问题描述

这个问题与Leetcode 88 相同。
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

  • The number of elements initialized in nums1 and nums2 are m and n respectively.
  • You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.

Example:

input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n=3

output: [1,2,2,3,5,6]

2 代码


def merge(nums1, m , nums2, n):
    if m and n:
        while m >0 and n >0:
            if nums1[m-1] >= nums2[n-1]:
                nums1[n+m-1] = nums1[m-1]
                m -=1
            else:
                nums1[n+m-1] = nums2[n-1]
                n -=1
    if n:
        nums1[:n] = nums2[:n]

3 分析

在合并两个数组(包括字符串)时,如果从前往后复制每个数字(或者字符),则需要重复移动多次;那么我们可以考虑从后往前复制,这样就能减少移动的次数,从而提高效率。

相关文章

网友评论

      本文标题:《剑指Offer》合并有序列表 Python实现

      本文链接:https://www.haomeiwen.com/subject/rixzrqtx.html