天天看點

【LeetCode】88.合并兩個有序數組

1. 題目

2. 分析

3. 代碼

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.
        """
        # 從後往前放置元素即可
        end1 = m - 1
        end2 = n - 1
        idx = len(nums1) - 1
        # 把所有的數放到nums1中
        while(end1>=0 and end2>=0):
            if nums1[end1] <= nums2[end2]:
                nums1[idx] = nums2[end2]
                end2 -= 1
            else:
                nums1[idx] = nums1[end1]
                end1 -= 1
            idx-=1
        while(end2>=0):
            nums1[idx] = nums2[end2]
            end2 -= 1
            idx-=1
        print(nums1)