[LeetCode-88] Merge Sorted Array(合并有序数组)

来源:互联网 发布:赈灾晚会的数据统计 编辑:程序博客网 时间:2024/04/30 15:17

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.
【分析】考虑从后往前比较,这样就不会产生需要数据后移的问题了。时间复杂度O(n+m),采用尾插法,这样就不再需要辅助空间的开销。
代码如下:

void merge(int nums1[], int m, int nums2[], int n) {    int index = m + n - 1;    int aIndex = m - 1;    int bIndex = n - 1;    /*考虑从后往前比较,这样就不会产生需要数据后移的问题了*/    while(0 <= aIndex && 0 <= bIndex)    {        if (nums2[bIndex] > nums1[aIndex])        {            nums1[index--] = nums2[bIndex--];        }        else        {            nums1[index--] = nums1[aIndex--];        }    }    while(0 <= aIndex)    {        nums1[index--] = nums1[aIndex--];    }    while(0 <= bIndex)    {        nums1[index--] = nums2[bIndex--];    }}
0 0