- 給定兩個有序整數數組nums1和nums2,合併nums1和nums2爲數組nums1
1:正序遍歷nums2,按從小到大的順序插入nums1中
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
count = 0
index = 0
while count<n:
if nums1[index]>nums2[count]:
nums1[index+1:m+count+1] = nums1[index:m+count]
nums1[index] = nums2[count]
count += 1
if index > m+count-1:
nums1[index] = nums2[count]
count += 1
index += 1
2:利用str.sort()方法
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
nums1[m:m+n] = nums2
return nums1.sort()
3:倒序遍歷nums1和nums2,按從大到小的順序插入sum1中
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
while n>0 and m>0:
if nums2[n-1]>nums1[m-1]:
nums1[m+n-1] = nums2[n-1]
n -= 1
else:
nums1[m+n-1] = nums1[m-1]
m -= 1
if n>0:
nums1[:n] = nums2[:n]
leecode題目