Merge Sorted Array

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]

Solutions

My solution

class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        int size = nums1.size();
        for(int i = 1; i <= m; ++i){
            nums1[size - i] = nums1[m - i];
        }
        int k = 0, i = size - m, j = 0;
        for(int k = 0; k < m + n; ++k){
            int a = i < size ? nums1[i] : INT_MAX;
            int b = j < n ? nums2[j] : INT_MAX;
            if(a < b){
                nums1[k] = a;
                ++i;
            }else{
                nums1[k] = b;
                ++j;
            }
        }
    }
};

Optimal solution

Credit: https://leetcode.com/problems/merge-sorted-array/discuss/29515/4ms-C++-solution-with-single-loop

Idea: process from large to small numbers.

class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        int i = m - 1, j = n - 1, k = m + n - 1;
        while(j >= 0){
            nums1[k--] = i >= 0 && nums1[i] > nums2[j] ? nums1[i--] : nums2[j--];
        }
    }
};

Last updated