LeetCode 88. Merge Sorted Array

栏目: 编程工具 · 发布时间: 6年前

内容简介:Given two sorted integer arrays给定两个有序整数数组思路很简单,先合并两个数组,再重新排序。注意,此题不需要返回。
LeetCode 88. Merge Sorted Array 题解

题目描述

  • 英文:

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 .
  • 中文:

给定两个有序整数数组 nums1nums2 ,将 nums2 合并到 nums1 使得 num1 成为一个有序数组。

说明:

  • 初始化 nums1nums2 的元素数量分别为 mn
  • 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n )来保存 nums2 中的元素。

示例

输入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6],       n = 3

输出: [1,2,2,3,5,6]

题解

  • 题解 1

思路很简单,先合并两个数组,再重新排序。注意,此题不需要返回。

class Solution:
    def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: void Do not return anything, modify nums1 in-place instead.
        """
        nums1[m:m + n] = nums2[:n]  # 将 nums2 中的数复制到 nums1 的后面
        nums1.sort()  # 重新排序
  • 题解 2

因为 nums1 的右端留有空位,而且两个数组都是排好序的,因此我们只要用两个指针,从两个数组的右端开始进行比较,得到较大的放到从 nums1 右边开始填充。最后如果 nums1 中已有的数都已经移动完成,而 nums2 中还有剩余,则直接将 nums2 的数复制到 nums1 的前面即可。

class Solution:
    def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: void Do not return anything, modify nums1 in-place instead.
        """
        i, j = m - 1, n - 1  # 从右边开始比较
        while i >= 0 and j >= 0:  # 直到最左边
            if nums1[i] > nums2[j]:  # 比较
                nums1[i + j + 1] = nums1[i]  # 填充预留的位置
                i -= 1
            else:
                nums1[i + j + 1] = nums2[j]  # 填充预留的位置
                j -= 1
        nums1[:j + 1] = nums2[:j + 1]  # 复制 nums2 中剩余的数

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

数据结构与算法分析

数据结构与算法分析

Mark Allen Weiss / 冯舜玺 / 电子工业出版社 / 2016-8 / 89.00元

本书是数据结构和算法分析的经典教材,书中使用主流的程序设计语言C++作为具体的实现语言。书中内容包括表、栈、队列、树、散列表、优先队列、排序、不相交集算法、图论算法、算法分析、算法设计、摊还分析、查找树算法、k-d树和配对堆等。本书把算法分析与C++程序的开发有机地结合起来,深入分析每种算法,内容全面、缜密严格,并细致讲解精心构造程序的方法。一起来看看 《数据结构与算法分析》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器