把归并结果存到第一个数组上:
Input: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6]
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. """ end=m+n-1 end_1=m-1 end_2=n-1 while(end_1>=0 and end_2>=0): if(nums1[end_1]>=nums2[end_2]): nums1[end]=nums1[end_1] end_1-=1 end-=1 else: nums1[end]=nums2[end_2] end_2-=1 end-=1 nums1[:end_2+1]=nums2[:end_2+1]
1.nums1[:end_2+1]=nums2[:end_2+1] 位置在while循环外面,也就是说,当end-1<0 或者 end-2<0 时候执行
2.用例如下时候:
[1,2,9,10,11,12] 3 [2,5,6] 3
[1,2,2,5,6,9]
原文:https://www.cnblogs.com/Mustardseed/p/12670656.html