[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 };

 

posted @ 2015-07-02 18:11  jianchao-li  阅读(176)  评论(0编辑  收藏  举报