---
# System prepended metadata

title: LeetCode 88. Merge Sorted Array
tags: [Leetcode]

---

---
title: 'LeetCode 88. Merge Sorted Array'
disqus: hackmd
---

# LeetCode 88. Merge Sorted Array



## Description

You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.

Merge nums1 and nums2 into a single array sorted in non-decreasing order.

The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.

## Example

Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
## Constraints

nums1.length == m + n
nums2.length == n
0 <= m, n <= 200
1 <= m + n <= 200
-10^9^ <= nums1[i], nums2[j] <= 10^9^

## Answer

此題將nums2和到nums1中然後排序即可。

```Cin=
void myqsort(int *nums,int left,int right);
void SWAP(int *a,int *b);

//2021_11_21
void merge(int* nums1, int nums1Size, int m, int* nums2, int nums2Size, int n){
    if(n != 0){
        int i = 0;
        for(i = m; i < m + n; i++){nums1[i] = nums2[i - m];}
    }
    myqsort(nums1, 0, m + n - 1);
}

void myqsort(int *nums,int left,int right){
    if(left<right){
        int L = left+1,R = right,pivot = left;
        while(L < R){
            while(L<right && nums[L] <= nums[pivot]){L++;}
            while(R>left && nums[R] >= nums[pivot]){R--;}
            if(L<R){SWAP(&nums[L], &nums[R]);}
        }
        if(nums[R] <= nums[pivot]){SWAP(&nums[pivot], &nums[R]);}
        myqsort(nums, left, R-1);
        myqsort(nums, R+1, right);
        
    }
}

void SWAP(int *a,int *b){
    int temp = *a;
    *a = *b;
    *b = temp;
}
```



## Link
https://leetcode.com/problems/merge-sorted-array/
###### tags: `Leetcode` 
