88. Merge Sorted Array

1. Description

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

2. 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.

3. Example

Example 1:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]

4. Constraints

  • $-10^9$ <= nums1[i], nums2[i] <= $10^9$
  • nums1.length == m + n
  • nums2.length == n

5. Solutions

My Accepted Solution

n = max(m_nums1.size(), i_nums2.size())
Time complexity: O(n)
Space complexity: O(1)

class Solution 
{
public:
    // void merge(vector<int>& nums1, int m, vector<int>& nums2, int n)
    void merge(vector<int> &m_nums1, int length1, const vector<int> &i_nums2, int length2) 
    {
        int mergedArrayIndex = length1 + length2 - 1, nums1Index = length1 - 1, nums2Index = length2 - 1;
        for( ;nums1Index >= 0 && nums2Index >= 0; mergedArrayIndex--)
        {
            m_nums1[mergedArrayIndex] = max(m_nums1[nums1Index], i_nums2[nums2Index]);
            
            m_nums1[nums1Index] <= i_nums2[nums2Index] ? nums2Index-- : nums1Index--;
        }
        
        for( ;nums2Index >= 0; mergedArrayIndex--, nums2Index--) 
        {
            m_nums1[mergedArrayIndex] = i_nums2[nums2Index];
        }
    }
};
comments powered by Disqus