leetcode88:合併兩個有序陣列
阿新 • • 發佈:2018-12-15
思想:
從nums1和nums2末尾的元素開始比較大小,大的則留在nums1[end]。
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. """ end = m+n-1 m = m-1 n = n-1 if m == -1: nums1[0] = nums2[0] while end >= 0 and m >= 0 and n >= 0: if nums1[m] > nums2[n]: nums1[end] = nums1[m] m = m-1 else: nums1[end] = nums2[n] n = n - 1 end = end-1 while n >= 0: nums1[end] = nums2[n] n = n-1 end = end-1
之前我比較喜歡用for迴圈套用,有的時候陣列下標變換並不是連續的,這是我借鑑大佬的while,感覺很好用。
比較大小一般也是喜歡從頭開始,這種題從末尾開始確是簡單不少。