Egbert Lin's Blog

“Life is not a race, but a journey to be savoured each step of the way” by Brian Dyson

[LeetCode Road] Merge Sorted Array - Solution/C++

88. Merge Sorted Array

Question:

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 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]

Constraints:
  • -10^9 <= nums1[i], nums2[i] <= 10^9
  • nums1.length == m + n
  • nums2.length == n
  • Source code

    Version 1

    Idea:
    My initial approach is to use queue to store element. The processing of merging is in order, I compare witch each elements, if the element is smaller, it will be assign to nums1[i] after the original value of index i will push to queue at nums vector. But, I faced many if statement in my code, it's too complicated.

    Finally, I refered to ChingYuanYang, I gained an impressive solution after realizing his explanation.
    I can assign the element from the last position in reverse order at nums1 vector that is the largest value. It's an easy way to merge vectors.

    Time complexity: O(m + n)
    Space complexity: O(1)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    class Solution {
    public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
    int s_1 = m -1;
    int s_2 = n -1;
    int max_size = m + n -1;
    for(int i = max_size; i >= 0; i--){
    if(s_1 < 0){
    nums1[i] = nums2[s_2--];
    }else if(s_2 < 0){
    nums1[i] = nums1[s_1--];
    }else if(nums1[s_1] > nums2[s_2]){
    nums1[i] = nums1[s_1--];
    }else{
    nums1[i] = nums2[s_2--];
    }
    }
    }
    };

    Version 2

    Idea:
    It's a perfert code from Huahua's Tech Road.

    According to the question, it says "merge nums2 into nums1", so we can use the size (=n) of nums2 as while statement rather than the size (=m+n) of nums1. Then, use only one statement to implement clean code with no if statement.

    Time complexity: O(m + n)
    Space complexity: O(1)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    class Solution {
    public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
    int i = m - 1;
    int j = n - 1;
    int tail = m + n - 1;
    while(j>=0){
    nums1[tail--] = (i >= 0 && nums1[i] > nums2[j]) ? nums1[i--] : nums2[j--];
    }
    }
    };