[LeetCode] Merge Sorted Array
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 };
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步