地址:点击打开链接
算法要求合并两个有序数组,其中将数组二的元素合并到数组1中,数据结构书中合并有序数组是新建一个数组,然后依次比较大小,这个题如果按照这种思路,明显时间复杂度是o(n*n),所以有一个简单的方法,从尾部开始比较,因为数组1的长度足够,所以设计从两个数相加的长度开始比较即可
不知道什么原因python的代码一直通不过,我写了个java的反倒过了
答案:
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.
"""
if n > 0 and m:
len1 = m - 1
len2 = n - 1
total = m + n - 1
while len2 >= 0 and len1 >= 0:
if nums1[len1] >= nums2[len2]:
nums1[total] = nums1[len1]
len1 -= 1
total -= 1
else:
nums1[total] = nums2[len2]
len2 -= 1
total -= 1
while len2 >= 0:
nums1[len2] = nums2[len2]
len2 -= 1
elif n > 0 and not m:
nums1 = nums2
else:
pass