标准库打败99%的人

LeetCode里的一道easy级别算法题——88. Merge Sorted Array。用python3标准库的sort()函数打败了99%的人。

题目描述

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

The number of elements initialized in nums1 and nums2 are m and n respectively.

You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.

Example:

1
2
3
4
5
6
7
Input:

nums1 = [1,2,3,0,0,0], m = 3

nums2 = [2,5,6], n = 3

Output: [1,2,2,3,5,6]

标准库实现

思路:

  1. 定义curr_index用来表示nums1的下标,初始值为m
  2. 遍历数组nums2中的所有元素,将他们依次放入nums1[m], nums1[m+1], …即nums1[curr_index]
  3. 调用sort()进行排序

代码如下:

1
2
3
4
5
6
7
class Solution:
def merge(self, nums1, m, nums2, n):
curr_index = m
for elem in nums2:
nums1[curr_index] = elem
curr_index += 1
nums1 = nums1.sort()

不用标准库实现

不用标准库也很简单,关键一点就是对各种边界值的判断,代码如下:

1
2
3
4
5
6
7
8
9
10
class Solution:
def merge(self, nums1, m, nums2, n):
while m > 0 and n > 0:
if nums1[m-1] >= nums2[n-1]:
nums1[m+n-1] = nums1[m-1]
m -= 1
else:
nums1[m+n-1] = nums2[n-1]
if n > 0: # 如果nums2中还有剩余的元素
nums1[:n] = nums2[:n]