【LeetCode 88 】 Merge Sorted Array

来源:互联网 发布:时间同步服务器软件 编辑:程序博客网 时间:2024/05/21 09:28
/*题目: LeetCode 88 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.*/#include<iostream>using namespace std;// 假设aDst有足够的内存存储两个数组合并后的结果void MergeSortedArray(int dst[], int src[],  int dstLength , int srcLength){    int iSrc = srcLength - 1;    int iDst = dstLength - 1;    int iTarget = srcLength + dstLength - 1;    while(iSrc >= 0 && iDst >= 0)    {        dst[iTarget--] = src[iSrc] > dst[iDst] ? src[iSrc--] : dst[iDst--];    }    while(iSrc >= 0)    {        dst[iTarget--] = src[iSrc--];    }}int main(){    int a[10] = {3,5, 6};    int b[4] = {2, 2, 4, 8};    for(int i = 0; i<10; i++)    {        cout << a[i] << ' ';    }    cout << endl;    MergeSortedArray(a, b, 3, 4);    for(int i = 0; i<10; i++)    {        cout << a[i] << ' ';    }    cout << endl;}

小结:
1)合并两个数组(包括字符串)时, 如果从前往后复制每个数字(或字符串)需要重复移动数字(或字符)多次, 那么我们可以考虑从后往前复制,这样就能减少移动的次数,从而提高效率;
2)这种反向思维很重要,往往由后往前更能得到优化的答案;

参考资料:
《剑指offer》 何海涛 老师
LeetCode

0 0