88. Merge Sorted Array

2,288次阅读
没有评论

共计 692 个字符,预计需要花费 2 分钟才能阅读完成。

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1as one sorted array.

Note:

  • The number of elements initialized in nums1 and nums2 are m and nrespectively.
  • 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]

这道题很蛋疼,它是预留足够的空间供你去使用,感觉像是合并排序,又不是那回事,仅OJ使用

class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        length=len(nums1)-1
        m-=1
        n-=1
        while m>=0 and n>=0:
            if nums1[m]>nums2[n]:
                nums1[length]=nums1[m]
                m-=1
            else:
                nums1[length]=nums2[n]
                n-=1
            length-=1
        while n>=0:
            nums1[length]=nums2[n]
            n-=1
            length-=1
正文完
请博主喝杯咖啡吧!
post-qrcode
 
admin
版权声明:本站原创文章,由 admin 2019-02-23发表,共计692字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码