首页 > 编程语言 > 详细

Leetcode-88(归并两个有序数组)

时间:2020-04-10 00:16:48      阅读:512      评论:0      收藏:0      [点我收藏+]

1.题目

把归并结果存到第一个数组上:

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

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

2.代码实现:

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.
        """
        end=m+n-1
        end_1=m-1
        end_2=n-1
        while(end_1>=0 and end_2>=0):
            if(nums1[end_1]>=nums2[end_2]):
                nums1[end]=nums1[end_1]
                end_1-=1
                end-=1
            else:
                nums1[end]=nums2[end_2]
                end_2-=1
                end-=1
        nums1[:end_2+1]=nums2[:end_2+1]

3.注意事项:

1.nums1[:end_2+1]=nums2[:end_2+1] 位置在while循环外面,也就是说,当end-1<0 或者 end-2<0 时候执行

2.用例如下时候:

[1,2,9,10,11,12]
3
[2,5,6]
3
[1,2,2,5,6,9]

 

Leetcode-88(归并两个有序数组)

原文:https://www.cnblogs.com/Mustardseed/p/12670656.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!