You are given two integer arrays nums1
and nums2
, sorted in non-decreasing order, and two integers m
and n
, representing the number of elements in nums1
and nums2
respectively.
The key is doing this reversely.
By this approach the time complexity is only O(n)
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.
"""
last = m + n - 1
m = m - 1
n = n - 1
while m >= 0 and n >= 0:
if nums1[m] > nums2[n]:
nums1[last] = nums1[m]
m -= 1
else:
nums1[last] = nums2[n]
n -= 1
last -= 1
while n >= 0:
nums1[last] = nums2[n]
n -= 1
last -= 1
搶先發佈留言