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源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。

相關文章
相關標籤/搜索