[LeetCode][88. Merge Sorted Array] 3 Approaches: Sorting, Two Pointers and Reverse Two Pointers
By Long Luo
This article is the solution 3 Approaches: Sorting, Two Pointers and Reverse Two Pointers of Problem 88. Merge Sorted Array .
Here shows 3 Approaches to slove this problem: Sorting, Two Pointers and Reverse Two Pointers.
Sorting
Let the array \(\textit{nums}_2\) into the rear of array \(\textit{nums}_1\), and then sort the entire array.1
2
3
4
5
6
7public static void merge_sort(int[] nums1, int m, int[] nums2, int n) {
for (int i = 0; i < n; i++) {
nums1[m + i] = nums2[i];
}
Arrays.sort(nums1);
}
Analysis
- Time Complexity: \(O((m + n)log(m+n))\) .
- Space Complexity: \(O(log(m+n))\) .
Two Pointers
Since two arrays \(\textit{nums}_1\) and \(\textit{nums}_2\) are both sorted in non-decreasing order, so we can use the Two Pointers method.
We consider the two arrays as two queues, takes the smaller numbers from the two arrays headers each round and put it into our results.