Leetcode 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.
nums1
and nums2
are already sorted?
nums1
(first m
elements) and nums2
are sorted in non-decreasing order.nums1
be negative?
nums1
?
nums1
without exceeding its length.p1
for nums1
and p2
for nums2
) and start comparing from the end of both arrays. This ensures that we utilize the empty spaces at the end of nums1
effectively.nums1
and fill in elements from the end to the beginning.p1
and p2
points to and place the larger element at the current end position.p
where the next element is to be placed.nums2
after p1
is exhausted, copy them directly into the starting positions in nums1
.public class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
// Pointers
int p1 = m - 1; // pointer for nums1
int p2 = n - 1; // pointer for nums2
int p = m + n - 1; // pointer for merged array
// Merge in reverse order
while (p1 >= 0 && p2 >= 0) {
if (nums1[p1] > nums2[p2]) {
nums1[p] = nums1[p1];
p1--;
} else {
nums1[p] = nums2[p2];
p2--;
}
p--;
}
// If there are remaining elements in nums2
while (p2 >= 0) {
nums1[p] = nums2[p2];
p2--;
p--;
}
}
}
nums1
and nums2
exactly once in a single pass, thus it’s O(m + n).nums1
in-place.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?