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.
Solution
Use two pointers to iterate over the arrays from the end. Compare the last element of both arrays and put the larger element at the end of the first array. Repeat until all elements are merged.
Implementation
Pseudocode
- Start from the end of the array.
- Compare the last element of both arrays.
- Put the larger element at the end of the first array.
- Repeat until all elements are merged.
Complexity Analysis
- Time complexity:
O(n)
. We are iterating over all the elements of the array. - Space complexity:
O(1)
. We are not using any extra space.