# https://walkccc.me/LeetCode/problems/0088/classSolution:defmerge(self,nums1: List[int],m:int,nums2: List[int],n:int) ->None: p1, p2 = m -1, n -1# destination d index to insert into nums1for d inrange(m + n -1, -1, -1):# if second list is empty, nothing more to mergeif p2 <0:return# only merge from nums1 if there are items left to merge# insert at d the larger of the two values from nums1 and nums2if p1 >=0and nums1[p1]> nums2[p2]: nums1[d]= nums1[p1] p1 -=1else: nums1[d]= nums2[p2] p2 -=1
时间复杂度:O(m+n)
空间复杂度:O(1)
classSolution:defmergeSortedArray(self,A,m,B,n): index = m + n -1 i = m -1 j = n -1while i >=0and j >=0:if A[i]>= B[j]: A[index]= A[i] i -=1else: A[index]= B[j] j -=1 index -=1while i >=0: A[index]= A[i] i -=1 index -=1while j >=0: A[index]= B[j] j -=1 index -=1