# 合并两个有序数组python_python算法题---合并两个有序数组

leetcode-python-合并两个有序数组

meage_sort.png

a = [1,2,3,4,5,6]

b = [2,4,6,8,9,10]

m = []

i,j = 0,0

a[i] < b[j] # 1<2

m.append(a.pop(i)) # m=[1]

a[i] == b[j] # 2 == 2

m.append(a[i]) # m = [1, 2]

a[i] > b[j] # 3 > 2

m.append(b[j]) # m = [1, 2, 2]

# 重复上面的步骤直到某个指针大于索引，将另一个列表中剩下的元素添加到m中

def merge_sort(nums1, nums2):

m = []

i, j = 0, 0

l_1, l_2 = len(nums1)-1, len(nums2)-1

# 当i，j的索引位置小于等于索引最大值的时候

while i <= l_1 and j <= l_2:

if nums1[i] <= nums2[j]:

m.append(nums1[i])

i += 1

else:

m.append(nums2[j])

j += 1

m = m + nums1[i:] + nums2[j:]

return m

if __name__ == '__main__':

n1 = [1, 2, 3, 4, 5]

n2 = [2, 4, 5, 6, 7]

m = merge_sort(n1, n2)

print(m)

# [1, 2, 2, 3, 4, 4, 5, 5, 6, 7]

def merge_sort(nums1, nums2):

m = []

i, j = 0, 0

while nums1 and nums2:

if nums1[i] <= nums2[j]:

temp = nums1.pop(i)

m.append(temp)

else:

temp = nums2.pop(j)

m.append(temp)

m = m + nums1 + nums2

return m

05-01 242
09-02 5155
02-28 1113
08-25 443
05-11 2665
01-09 239
01-19
04-30 1万+