给你两个有序整数数组 nums1 和 nums2,请你将 nums2 合并到 nums1 中,使 nums1 成为一个有序数组。(老规矩第一个我写的,后面一个我更具其他人改的)
class Solution(object):
def merge1(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.
"""
if m == 0:
nums1[:] = nums2[:]
else:
length = len(nums1) - 1
while nums2:
while n > 0 and m > 0 and nums2 and nums1[m - 1] <= nums2[n - 1]:
nums1[length] = nums2.pop()
length -= 1
n -= 1
while n > 0 and m > 0 and nums2 and nums1[m - 1] > nums2[n - 1]:
nums1[length] = nums1[m - 1]
nums1[length - 1] = nums1[m - 2]
length -= 1
m -= 1
if length == n - 1:
nums1[:n] = nums2[:n]
nums2 = []
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.
"""
if m == 0:
nums1[:] = nums2[:]
else:
length = len(nums1) - 1
while n > 0 and m > 0:
if nums1[m-1] <= nums2[n-1]:
nums1[length] = nums2.pop()
length -= 1
n -= 1
else:
nums1[length] = nums1[m-1]
length -= 1
m -= 1
nums1[:n] = nums2[:n]
if __name__ == '__main__':
s1 = Solution()
nums1 = [2, 3, 4, 0, 0]; m = 3
nums2 = [0, 1]; n = 2
s1.merge(nums1, m, nums2, n)
print(nums1)]