数组-LeetCode88-Merge Sorted Array

题意:给定两个排序的整数数组nums1nums2,将nums2合并为nums1作为一个排序的数组。

解题:因为自己是菜鸟一只,不知道为什么先合并两个数组,然后在排序不合理。看了好多网友的答案,感觉下面这个最靠谱。用两个参数(index1、index2)分别来表示nums1和nums2的下标,从两个数组的最大值开始比较,大的放在num1的最后,并将相应的参数-1(即已经记录的数组,向前移动一位),直至有一个参数小于0。如果是index1小于0,就说明nums2中还有数没有合并在nums1中,用切片将nums2中剩余的数放进nums1中即可;如果是index2小于0,说明nums2已经按照顺序放入nums1中了,原本nums1中的元素位置不用改变,直接得到正确的结果。

class Solution:
    def merge(self, nums1, m, nums2, n):

        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: void Do not return anything, modify nums1 in-place instead.
        """

        index1 = m - 1
        index2 = n - 1
        while index1>=0 and index2>=0:
            if nums1[index1]>nums2[index2]:
                nums1[index1+index2+1]=nums1[index1]
                index1-=1
            else:
                nums1[index1+index2+1]=nums2[index2]
                index2-=1
       
#如果是index1<0,将nums2中剩余的数,通过切片放到nums1中。
        #如果是index2<0, 则不进行操作。

        nums1[:index2+1]=nums2[:index2+1]

     

猜你喜欢

转载自blog.csdn.net/sjzuliguoku/article/details/81487835
今日推荐