zoukankan      html  css  js  c++  java
  • Leetcode-88(归并两个有序数组)

    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]
  • 相关阅读:
    DP实验
    Linux shell学习
    线性排序算法-计数排序
    算法笔试题练习
    堆排序
    node.js初识
    linux下vim命令详解
    html5学习笔记
    有趣的参数收集
    算法学习-归并排序
  • 原文地址:https://www.cnblogs.com/Mustardseed/p/12670656.html
Copyright © 2011-2022 走看看