您的位置:首页 > 其它

[LeetCode] Merge Sorted Array

2015-07-02 18:11 344 查看
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.

class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int p = m + n - 1, p1 = m - 1, p2 = n - 1;
while (p1 >= 0 && p2 >= 0) {
if (nums1[p1] >= nums2[p2])
nums1[p--] = nums1[p1--];
else nums1[p--] = nums2[p2--];
}
while (p2 >= 0)
nums1[p--] = nums2[p2--];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: