---
tags: LeetCode
---
# 88. 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 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]
輸入範本如下
```C#
public class Solution {
public void Merge(int[] nums1, int m, int[] nums2, int n) {
}
}
```
### 直覺想法
由 nums1 最右邊開始排大小 . 較大的先排入.
```C#
時間複雜度 O(m+n)
空間複雜度 O(1)
220 ms 30.5 MB
You are here!
Your runtime beats 99.74 % of csharp submissions.
public void Merge(int[] nums1, int m, int[] nums2, int n)
{
int totalIndex = m + n - 1, n1Index = m - 1, n2Index = n - 1;
// 由最右邊開始比較 , 較大的先排入 num1[totalIndex]
while (n1Index >= 0 && n2Index >= 0)
{
nums1[totalIndex--] = nums1[n1Index] >= nums2[n2Index] ? nums1[n1Index--] : nums2[n2Index--];
}
//while (n1Index >= 0) // num2 已經排完了 , 但 num1 還沒 . 但不需要排 , 因為已經在位子上了
//{
// nums1[totalIndex--] = nums1[n1Index--];
//}
while (n2Index >= 0) // num1 已經排完了 , 但 num2 還沒
{
nums1[totalIndex--] = nums2[n2Index--];
}
}
```
### Thank you!
You can find me on
- [GitHub](https://github.com/s0920832252)
- [Facebook](https://www.facebook.com/fourtune.chen)
若有謬誤 , 煩請告知 , 新手發帖請多包涵
# :100: :muscle: :tada: :sheep: