题目链接
https://leetcode.com/problems/merge-sorted-array/
题目原文
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one 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.
"""
tmp = [0 for i in range(m + n)]
i = 0
j = 0
k = 0
while i < m and j < n:
if nums1[i] <= nums2[j]:
tmp[k] = nums1[i]
i += 1
else:
tmp[k] = nums2[j]
j += 1
k += 1
if i == m:
while k < m + n:
tmp[k] = nums2[j]
k += 1
j += 1
else:
while k < m + n:
tmp[k] = nums1[i]
i += 1
k += 1
for i in range(0, m + n):
nums1[i] = tmp[i]