程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> LeetCode Merge Sorted Array

LeetCode Merge Sorted Array

編輯:C++入門知識

LeetCode Merge Sorted Array


LeetCode解題之Merge Sorted Array


原題

將兩個有序數組合並成為一個。

注意點:

第一個數組有充足的空間來存放第二個數組中的元素 第一個數組的有效長度為m,第二個的有效長度為n 在原數組上修改,沒有返回值

例子:

輸入: nums1 = [1, 1, 2, 2, 4, 0, 0, 0, 0], m = 5, nums2 = [0, 0, 2, 3], n = 4

輸出: 無(nums1變為[0, 0, 1, 1, 2, 2, 2, 3, 4])

解題思路

知道兩個數組原先的長度,就可以知道合並後的長度,倒敘遍歷兩個數組,大的數優先放到合並後的數組對應下標處。如果第一個數組先遍歷完,那應該把第二個數組剩下的元素復制過來;如果第二個先遍歷玩,就不用變化了,因為第一個數組剩余的元素已經在目標位置。

AC源碼

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: void Do not return anything, modify nums1 in-place instead.
        """
        index = m + n - 1
        m -= 1
        n -= 1
        while m >= 0 and n >= 0:
            if nums1[m] > nums2[n]:
                nums1[index] = nums1[m]
                m -= 1
            else:
                nums1[index] = nums2[n]
                n -= 1
            index -= 1
        if m < 0:
            nums1[:n + 1] = nums2[:n + 1]


if __name__ == "__main__":
    num1 = [1, 1, 2, 2, 4, 0, 0, 0, 0]
    num2 = [0, 0, 2, 3]
    Solution().merge(num1, 5, num2, 4)
    assert num1 == [0, 0, 1, 1, 2, 2, 2, 3, 4]

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved