LeetCode练题——88. Merge Sorted Array

1、题目

88. Merge Sorted Array——Easy

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 # -*- coding: utf-8 -*-
 2 # @Time    : 2020/2/16 19:18
 3 # @Author  : SmartCat0929
 4 # @Email   : [email protected]
 5 # @Link    : https://github.com/SmartCat0929
 6 # @Site    : 
 7 # @File    : 88. Merge Sorted Array.py
 8 from typing import List
 9 
10 
11 class Solution:
12     def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
13         """
14         Do not return anything, modify nums1 in-place instead.
15         """
16         p = m + n - 1
17         p1 = m - 1
18         p2 = n - 1
19         while p1 >= 0 and p2 >= 0:
20             if nums2[p2] > nums1[p1]:
21                 nums1[p] = nums2[p2]
22                 p -= 1
23                 p2 -= 1
24             else:
25                 nums1[p] = nums1[p1]
26                 p -= 1
27                 p1 -= 1
28         while p2 >= 0:
29             nums1[p] = nums2[p2]
30             p -= 1
31             p2 -= 1
32 
33 
34 Solution().merge([1, 2, 5, 0, 0, 0], 3, [2, 5, 6], 3)

猜你喜欢

转载自www.cnblogs.com/Smart-Cat/p/12318667.html