Skip to main content

0088 - Merge Sorted Array

大意來說

其實還滿簡單的...如果你排序演算法都沒有忘記的話

直接看輸出:

Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.

就是通通要把東西合併到 nums1 然後做 sort 就好

相關 Code

因為連最簡單的泡沫排序都忘記了,所以其實花很久時間處理 XD

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.
        """

        for i in range(m, m+n):
            nums1[i] = nums2[m - i]

        # Sort: Bubble sort
        temp_index = 0
        for i in range(0, m+n - 1):
            for j in range(0, m+n - 1 - i):
                if nums1[j] > nums1[j + 1]:
                    temp = nums1[j]
                    nums1[j] = nums1[j + 1]
                    nums1[j + 1] = temp
        

是時候該來去惡補排序演算法了...。