# [88\. Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/)
:::spoiler Hint - Sort
```cpp=
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n)
{
// Loop through each element in nums2 and copy it to the end of nums1
for ()
{
// Place the element from nums2 into the correct position in nums1
}
// Sort nums1 to merge the two arrays
}
};
```
:::
:::spoiler Solution - Sort
```cpp=
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n)
{
for (int i = 0; i < n; ++i)
{
nums1[m + i] = nums2[i];
}
sort(nums1.begin(), nums1.end());
}
};
```
- 時間複雜度:$O(N \cdot \log N)$
- 空間複雜度:$O(N)$
:::
:::spoiler Hint - Two Pointers
```cpp=
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n)
{
// Initialize three pointers:
// i - points to the last element of the initialized part of nums1
// j - points to the last element of nums2
// k - points to the last element of the merged array in nums1
// Merge nums1 and nums2 from the end to the beginning
while ()
{
// Compare the elements pointed by i and j
// Place the larger element at position k in nums1
// Copy element from nums1 and move pointers i and k
// Copy element from nums2 and move pointers j and k
}
// If there are remaining elements in nums2, copy them
// This is needed because the remaining elements of nums1 are already in place
}
};
```
:::
:::spoiler Solution - Two Pointers
```cpp=
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n)
{
int i = m - 1, j = n - 1, k = m + n - 1;
while (i >= 0 && j >= 0)
{
if (nums1[i] > nums2[j]) nums1[k--] = nums1[i--];
else nums1[k--] = nums2[j--];
}
while (j >= 0) nums1[k--] = nums2[j--];
}
};
```
- 時間複雜度:$O(N + M)$
- 空間複雜度:$O(M)$
:::