Problem: 88. 合并两个有序数组
思路
遍历两个数组,谁小用谁,放到另一个数组中,即可。
坑点:
- 题目要求不return结果,直接返回原来的输入参数nums1,在python中不能nums1 = nums 这样赋值不会改变原来的输入参数,需要一个一个的复制
- python 不能用i++,这个很烦
错误代码1
还是想的太简单了,思路一下子就有了,但是循环的条件写错了,改成while(i < m and j < n):
就可以了
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.
"""
i = j = 0
nums = []
while(i < min(m, n) and j < min(m, n)):
if nums1[i] < nums2[j]:
nums.append(nums1[i])
i += 1
else:
nums.append(nums2[j])
j += 1
while(i < m):
nums.append(nums1[i])
i += 1
while(j < n):
nums.append(nums2[j])
j += 1
for i in range(n + m):
nums1[i] = nums[i]