88. Merge Sorted Array
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
- The number of elements initialized in nums1 and nums2 are m and n respectively.
- You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from nums2.
合并两个排序数组,把第二个合并到第一个里面,保证第一个长度是够的。
用3个指针搞定,第一个指针=n+m-1,是从后往前指向nums1的,用来插入nums1或者nums2的数,第二个指针=m-1是从后往前指向nums1的,第三个指针=n-1是从后往前指向nums2的,
每次比较第二个指针和第三个指针的数,谁大就往第一个指针的位置插入值。因为从后往前,不会出现覆盖问题。
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: None Do not return anything, modify nums1 in-place instead. """ index = m + n - 1 index1 = m - 1 index2 = n - 1 while index1 >= 0 and index2 >= 0: if nums1[index1] > nums2[index2]: nums1[index] = nums1[index1] index -= 1 index1 -= 1 else: nums1[index] = nums2[index2] index -= 1 index2 -= 1 while index1 >= 0: nums1[index] = nums1[index1] index -= 1 index1 -= 1 while index2 >= 0: nums1[index] = nums2[index2] index -= 1 index2 -= 1