# 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;


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET 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?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
