LSGO——LeetCode實戰(數組系列):88題 合併兩個有序數組(Merge Sorted Array)

題目:

給定兩個有序整數數組 nums1 和 nums2,將 nums2 合併到 nums1 中,使得 num1 成爲一個有序數組。

說明:

初始化 nums1 和 nums2 的元素數量分別爲 m 和 n。
你可以假設 nums1 有足夠的空間(空間大小大於或等於 m + n)來保存 nums2 中的元素。

首選,我們需要先來理解一下題意,將有序數組合nums2併到有序數組nums1,實際上nums1數組index從m向後的0都可以理解爲空,前面m個纔是具體的元素.

我的解題思路:

使用三個遊標分別指向nums1元素位置(index),nums2元素位置(index_2),nums1中視爲空元素的0(index_null).

程序邏輯並不複雜,所以我就不解釋了。

class Solution(object):
    def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: None Do not return anything, modify nums1 in-place instead.
        """
        index =0
        index_null = m
        index_2 = 0
        while index_2< len(nums2):
            if nums1[index]> nums2[index_2]:
                nums1.insert(index,nums2[index_2])
                nums1.pop()
                index +=1
                index_2 +=1
                index_null +=1
            elif nums1[index] == 0 and index == index_null:
                nums1.insert(index,nums2[index_2])
                nums1.pop()
                index +=1
                index_2 +=1
                index_null +=1
            else:
                index +=1
        return nums1

注意點:

  • 當nums1[index]==0且index==index_null時,這說明此時nums1原元素已經遍歷完成,之後的步驟都是將nums2的元素插入nums1中。
  • 當我們插入一個元素之後,需要將index_null加1,因爲此時nums1中新插入了一個元素,所以空的遊標應當往後移一格。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章