注意循环结束条件
# coding=utf-8
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.class Solution:
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.
当需要插入的时候执行m-i+j次
最后一个空位的索引m+j-1
m+j-i-2次
"""
i=j=0
while j<n:
if i==m+j:
nums1[i]=nums2[j]
i+=1
j+=1
else:
if nums2[j] <= nums1[i]:
for offset in range(m+j-i):
last_idx=m+j
nums1[last_idx-offset]=nums1[last_idx-offset-1]
nums1[i]=nums2[j]
j+=1
else:
i+=1
return nums1