题目来源
https://leetcode.com/problems/merge-sorted-array/
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 nums1and nums2 are m and n respectively.
题意分析
Input:
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
Output:
:rtype: void Do not return anything, modify nums1 in-place instead.
Conditions:合并两个sorted的list,注意是将nums2合并进nums1当中,结果也必须是sorted,不返回任何元素。
题目思路
注意到nums1是有足够的空间存储m+n个元素的,所以直接对nums1进行操作就好,选择从数值较大的位置开始选择元素。
备注:如果n小于0了,就不需要继续合并了。
AC代码(Python)
1 class Solution(object): 2 def merge(self, nums1, m, nums2, n): 3 """ 4 :type nums1: List[int] 5 :type m: int 6 :type nums2: List[int] 7 :type n: int 8 :rtype: void Do not return anything, modify nums1 in-place instead. 9 """ 10 all = m + n - 1 11 m = m - 1 12 n = n - 1 13 while m >= 0 and n >= 0: 14 if nums1[m] > nums2[n]: 15 nums1[all] = nums1[m] 16 m = m - 1 17 all = all - 1 18 else: 19 nums1[all] = nums2[n] 20 n = n - 1 21 all = all - 1 22 while n >= 0: 23 nums1[all] = nums2[n] 24 all = all - 1 25 n = n - 1 26 27 28
时间: 2024-10-04 18:24:48