Merge Sorted Array
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: void Do not return anything, modify nums1 in-place instead.
"""
"""
for i in xrange(len(nums2)):
#nums1.append(nums2[i]) #要注意nums1的长度,如果nums1长度为0,即使里面有item,例如[1]m=0,则返回错误答案。
nums1[i+m] = nums2[i]
return nums1.sort()
"""
end = m+n-1
l1=m-1
l2 = n-1
while end >= 0:
if l1>=0 and l2>=0: #if nums1 and nums2 are left
if nums1[l1] > nums2[l2]:
nums1[end] = nums1[l1]
l1 -= 1
else:
nums1[end] = nums2[l2]
l2 -= 1
elif l1>=0 and l2 < 0: #if nums1 left
nums1[end] = nums1[l1]
l1 -= 1
elif l2>=0 and l1<0: #if nums2 left
nums1[end] = nums2[l2]
l2 -=1
end -= 1Last updated