---
description: easy 原题链接：https://leetcode.com/problems/merge-sorted-array/
---

# Merge Sorted Array

## Merge Sorted Array

原题链接：[https://leetcode.com/problems/merge-sorted-array/](https://leetcode.com/problems/merge-sorted-array/)

### 描述

> 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 **equal** to _m_ + _n_) to hold additional elements from _nums2_.

### 例子

> Input:&#x20;
>
> nums1 = \[1,2,3,0,0,0], m = 3&#x20;
>
> nums2 = \[2,5,6], n = 3
>
> Output: \[1,2,2,3,5,6]

### 约束条件

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

### 解法一

```
class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        int i=0;
        while(i<n){
            nums1[m+i]=nums2[i];
            i++;
        }
        sort(nums1.begin(), nums1.end());
    }
};
```

### 解法二

```
class Solution {
public:
    void merge(vector<int>& A, int m, vector<int>& B, int n) {
        int i=m-1;
		int j=n-1;
		int k = m+n-1;
		while(i >=0 && j>=0)
		{
			if(A[i] > B[j])
				A[k--] = A[i--];
			else
				A[k--] = B[j--];
		}
		while(j>=0)
			A[k--] = B[j--];
    }
};
```
