Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
题意:
给两个有序数组 nums1、nums2,将两个数组原地合并到 nums1,保持 nums1 有序。
Solution
与归并排序类似,但是从头部开始归并的成本太高,而 nums1 又有足够的长度,因此从两数组的尾部开始归并,放在 nums1 尾部(从 m + n - 1 开始)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class(object):
defmerge(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.
近期评论