LeetCode刷题实战88:合并两个有序数组

算法的重要性,我就很少说了吧,想去大厂,就必需要通过基础知识和业务逻辑面试+算法面试。因此,为了提升你们的算法能力,这个公众号后续天天带你们作一道算法题,题目就从LeetCode上面选 !web

今天和你们聊的问题叫作 合并两个有序数组,咱们先来看题面:面试

https://leetcode-cn.com/problems/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.app

You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from nums2.url

题意


给你两个有序整数数组 nums1 和 nums2,请你将 nums2 合并到 nums1 中,使 nums1 成为一个有序数组。

说明:初始化 nums1 和 nums2 的元素数量分别为 m 和 n 。
你能够假设 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]spa


解题


方法一 : 合并后排序

最朴素的解法就是将两个数组合并以后再排序。,时间复杂度较差,为O((n+m)log(n+m))。这是因为这种方法没有利用两个数组自己已经有序这一点。

class Solution {
  public void merge(int[] nums1, int m, int[] nums2, int n) {
    System.arraycopy(nums2, 0, nums1, m, n);
    Arrays.sort(nums1);
  }
}.net


方法二 : 双指针 / 从前日后

通常而言,对于有序数组能够经过 双指针法 达到O(n + m)的时间复杂度。
最直接的算法实现是将指针p1 置为 nums1的开头, p2为 nums2的开头,在每一步将最小值放入输出数组中。
因为 nums1 是用于输出的数组,须要将nums1中的前m个元素放在其余地方,也就须要 O(m)的空间复杂度。


class Solution {
  public void merge(int[] nums1, int m, int[] nums2, int n) {
    // Make a copy of nums1.
    int [] nums1_copy = new int[m];
    System.arraycopy(nums1, 0, nums1_copy, 0, m);

    // Two get pointers for nums1_copy and nums2.
    int p1 = 0;
    int p2 = 0;

    // Set pointer for nums1
    int p = 0;

    // Compare elements from nums1_copy and nums2
    // and add the smallest one into nums1.
    while ((p1 < m) && (p2 < n))
      nums1[p++] = (nums1_copy[p1] < nums2[p2]) ? nums1_copy[p1++] : nums2[p2++];

    // if there are still elements to add
    if (p1 < m)
      System.arraycopy(nums1_copy, p1, nums1, p1 + p2, m + n - p1 - p2);
    if (p2 < n)
      System.arraycopy(nums2, p2, nums1, p1 + p2, m + n - p1 - p2);
  }
}3d


好了,今天的文章就到这里,若是以为有所收获,请顺手点个在看或者转发吧,大家的支持是我最大的动力。


上期推文:

LeetCode50-80题汇总,速度收藏!
LeetCode刷题实战81:搜索旋转排序数组 II
LeetCode刷题实战82:删除排序链表中的重复元素 II
LeetCode刷题实战83:删除排序链表中的重复元素
LeetCode刷题实战84: 柱状图中最大的矩形
LeetCode刷题实战85:最大矩形
LeetCode刷题实战86:分隔链表
LeetCode刷题实战87:扰乱字符串

本文分享自微信公众号 - 程序IT圈(DeveloperIT)。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。

相关文章
相关标签/搜索