# 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

```cpp
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](https://leetcode.com/problems/merge-sorted-array/discuss/29515/4ms-C++-solution-with-single-loop)

Idea: process from large to small numbers.

```cpp
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--];
        }
    }
};
```
