[LeetCode] Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.

归并两个已经排序好的数组,因为要把nums2中的数归并到nums1中,且nums1的数组大小没有限制,所以需要确定最终归并后的nums1的大小m+n-1,然后将两个数组的数组归并重新放去nums1中。

class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        int i = m - 1, j = n - 1, cur = m + n - 1;
        while (j >= 0) {
            nums1[cur--] = i >= 0 && nums1[i] > nums2[j] ? nums1[i--] : nums2[j--];
        }
    }
};
// 3 ms

 

posted @ 2017-11-10 09:55  immjc  阅读(106)  评论(0)    收藏  举报