> For the complete documentation index, see [llms.txt](https://r24zeng.gitbook.io/leetcode-notebook/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://r24zeng.gitbook.io/leetcode-notebook/wan-quan-an-zhao-jiu-zhang-suan-fa-shua-de-60-dao-zuo-you/ii.-sorted-array/88.-merge-sorted-array.md).

# 88. Merge Sorted Array

{% hint style="success" %}
Merge to nums1 from the end to beginning.

逆向思维
{% endhint %}

{% tabs %}
{% tab title="Java" %}

```java
class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int p1 = m - 1, p2 = n - 1, p = m + n - 1;;
        while(p1 >= 0 && p2 >= 0) {
            if(nums1[p1] >= nums2[p2]) {
                nums1[p] = nums1[p1];
                p1 --;
            } else {
                nums1[p] = nums2[p2];
                p2 --;
            }
            p --;
        }
        
        while(p2 >= 0) {
            nums1[p] = nums2[p2];
            p2 --;
            p --;
        }
    }
}
```

{% endtab %}

{% tab title="Python" %}

```python
// python
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None
    # merge from end to beginning
    i = m-1
    j = n-1
    p = m+n-1
        
    while i >= 0 and j >= 0:
        if nums1[i] > nums2[j]:
            nums1[p] = nums1[i]
            i = i-1
        else:
            nums1[p] = nums2[j]
            j = j-1
            p = p-1
    # only care when nums2 still has waiting elements
    if i < 0:
        for x in range(0, j+1):
            nums1[x] = nums2[x]
```

{% endtab %}
{% endtabs %}

Time complexity: $$O(n+m)$$&#x20;
