[LeetCode] Merge Sorted Array

88. Merge Sorted Array

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.

Follow up: Can you come up with an algorithm that runs in O(m + n) time?

  • Time : O(n + m)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
if(!n) return;
int p1 = m -1, p2 = n - 1;
for(int i = m + n - 1; i >= 0 and p1 >= 0 and p2 >= 0; i--) {
if(nums1[p1] >= nums2[p2]) {
nums1[i] = nums1[p1--];
} else {
nums1[i] = nums2[p2--];
}
}
for(int i = 0; i <= p2; i++) {
nums1[i] = nums2[i];
}
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/09/PS/LeetCode/merge-sorted-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.