原题目
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:
Input: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6]
思路
边界条件:nums1 == None 或者 nums2 == None
将 nums2 中的元素放到 nums1 里面再进行排序
如果 nums1 的长度大于 m+n,排序后多余的 0 会排在前面,因此将多余的 0 先设为 2 的 32 次方,排序完成后再恢复为 0
第一遍解法
# Runtime: 28 ms, faster than 99.82% of Python3 O(nlogn)
# Memory Usage: 13.1 MB, less than 80.27% of Python3 S(1)
class Solution:
def merge(self, nums1, m, nums2, n):
"""
Do not return anything, modify nums1 in-place instead.
"""
if nums1 == None or nums2 == None:
return nums1 or nums2
more_length = len(nums1) - m - n
for i in range(1, more_length+1): # 将多余的数设为 2的32次方
nums1[-i] = 2 ** 32
for index, num in enumerate(nums2):
nums1[m+index] = num
nums1.sort()
for i in range(1, more_length+1): # 还原为 0
nums1[-i] = 0
网上好的解法
和两条有序链表的排序思想相同,不同的是链表排序是从前向后,这里数组排序是从后往前
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
int i = m-1;
int j = n-1;
int k = m+n-1;
while(i >=0 && j>=0)
{
if(A[i] > B[j])
A[k--] = A[i--];
else
A[k--] = B[j--];
}
while(j>=0)
A[k--] = B[j--];
}
};
Pythonic 方法
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]
n -= 1
if n > 0:
nums1[:n] = nums2[:n]
自己可以改进的地方
最简代码