跳至主要内容

88. Merge Sorted Array

Hint - Sort

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
}
};
  • Sort
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());
}
};
  • T: O(NlogN)O(N \cdot \log N)
  • S: O(N)O(N)

Hint - Two Pointers

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
}
};
  • Two Pointers
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--];
}
};
  • T: O(N+M)O(N + M)
  • S: O(M)O(M)