LeetCode 88. Merge Sorted Array

简介: 题意是给定了两个排好序的数组,让把这两个数组合并,不要使用额外的空间,把第二个数组放到第一个数组之中.

v2-a94c5acf7443be7b8da13136dd84423b_1440w.jpg


Description



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,长度m,数组nums2,长度n,我们从两个数组的末尾,p,q开始比较,我们把较大的数放在p+q+1的位置.
  • 如此循环,最后把nums2剩下的元素放到nums1即可.


# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2018-12-25 17:10:16
# @Last Modified by:   何睿
# @Last Modified time: 2018-12-25 17:10:16
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.
        """
        # p,q分别指向数组的最后一个位置.
        p, q = m-1, n-1
        # 当数组不为空的才进行循环.
        while p >= 0 and q >= 0:
            # 把较大的数放在末尾
            if nums1[p] > nums2[q]:
                nums1[p+q+1] = nums1[p]
                p = p-1
            else:
                nums1[p+q+1] = nums2[q]
                q = q-1
        # 把nums2剩下的元素放在nums1中.
        nums1[:q+1] = nums2[:q+1]
if __name__ == "__main__":
    so = Solution()
    nums1 = [1, 2, 3, 0, 0, 0]
    nums2 = [2, 5, 6]
    so.merge(nums1, 3, nums2, 3)
    print(nums1)


源代码文件在这里.

目录
相关文章
|
8月前
Leetcode 4. Median of Two Sorted Arrays
题目描述很简单,就是找到两个有序数组合并后的中位数,要求时间复杂度O(log (m+n))。 如果不要去时间复杂度,很容易就想到了归并排序,归并排序的时间复杂度是O(m+n),空间复杂度也是O(m+n),不满足题目要求,其实我开始也不知道怎么做,后来看了别人的博客才知道有个二分法求两个有序数组中第k大数的方法。
19 0
|
8月前
Leetcode Find Minimum in Rotated Sorted Array 题解
对一个有序数组翻转, 就是随机取前K个数,移动到数组的后面,然后让你找出最小的那个数,注意,K有可能是0,也就是没有翻转。
28 0
Search in Rotated Sorted Array - 循环有序数组查找问题
Search in Rotated Sorted Array - 循环有序数组查找问题
55 0
LeetCode 167 Two Sum II - Input array is sorted(输入已排序数组,求其中两个数的和等于给定的数)
给定一个有序数组和一个目标值 找出数组中两个成员,两者之和为目标值,并顺序输出
66 0
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
|
算法 Python
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
|
算法 测试技术
LeetCode 88. 合并两个有序数组 Merge Sorted Array
LeetCode 88. 合并两个有序数组 Merge Sorted Array
|
20天前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-2
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题
|
20天前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-1
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题
|
21天前
|
索引
【LeetCode刷题】二分查找:山脉数组的峰顶索引、寻找峰值
【LeetCode刷题】二分查找:山脉数组的峰顶索引、寻找峰值