算法学习

算法题--合并有序数组

2020-04-25  本文已影响0人  岁月如歌2020
image.png

0. 链接

题目链接

1. 题目

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]

2. 思路1:逐个比较最后一个元素, 将大数放入nums1尾部

3. 代码

# coding:utf8
from typing import List


class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        while n > 0 and m > 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:
            for i in range(n):
                nums1[i] = nums2[i]


def my_test(solution, nums1, m, nums2, n):
    print('input: nums1={}, m={}, nums2={}, n={}'.format(nums1, m, nums2, n))
    solution.merge(nums1, m, nums2, n)
    print('output: {}'.format(nums1))


solution = Solution()
my_test(solution, [1, 2, 3, 0, 0, 0], 3, [2, 5, 6], 3)
my_test(solution, [2,0], 1, [1], 1)
my_test(solution, [1], 1, [], 0)


输出结果

input: nums1=[1, 2, 3, 0, 0, 0], m=3, nums2=[2, 5, 6], n=3
output: [1, 2, 2, 3, 5, 6]

input: nums1=[2, 0], m=1, nums2=[1], n=1
output: [1, 2]

input: nums1=[1], m=1, nums2=[], n=0
output: [1]

4. 结果

image.png
上一篇 下一篇

猜你喜欢

热点阅读