A classic subroutine of merge sort. Just merge the elements from back to forth. Keep a pointer for the merged position of the element and two other pointers for elements in nums1 and nums2 respectively.
The code is as follows.
1 class Solution { 2 public: 3 void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { 4 int p = m + n - 1, p1 = m - 1, p2 = n - 1; 5 while (p1 >= 0 && p2 >= 0) { 6 if (nums1[p1] >= nums2[p2]) 7 nums1[p--] = nums1[p1--]; 8 else nums1[p--] = nums2[p2--]; 9 } 10 while (p2 >= 0) 11 nums1[p--] = nums2[p2--]; 12 } 13 };
本文详细介绍了一种经典的归并排序子程序实现方法,该方法从数组尾部开始比较并合并两个已排序数组。通过使用三个指针分别指向合并后的数组位置及两个待合并数组的元素,实现了高效的数组合并。
322

被折叠的 条评论
为什么被折叠?



