码迷,mamicode.com
首页 > 编程语言 > 详细

LeetCode-Merge Sorted Array-合并有序表-归并排序

时间:2014-10-15 23:05:41      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   使用   ar   for   sp   

https://oj.leetcode.com/problems/merge-sorted-array/

归并排序的一步操作,需要事先把A[]的元素移到数组末端,前段空出来填充结果。需要注意的是如果从0~m的转移会在n比较小的时候有问题。所以要从m~0转移。使用memcpy在GCC下就是从0~m开始转移,这个行为跟MSVC不一样。

class Solution {
public:
    void merge(int A[], int m, int B[], int n) {
        //memcpy(A+n,A,m*sizeof(int));  //error in gcc, succeed in msvc because of filling order
        for(int i=m-1;i>=0;i--) A[i+n]=A[i];
        int p=n;
        int q=0;
        int r=0;
        while(p<n+m && q<n){
            if (A[p]>B[q]) {
                A[r]=B[q];
                r++;q++;
            }
            else {
                A[r]=A[p];
                r++;p++;
            }
        }
        while(p<n+m) A[r++]=A[p++];
        while(q<n) A[r++]=B[q++];
    }
};

 

LeetCode-Merge Sorted Array-合并有序表-归并排序

标签:style   blog   http   color   io   使用   ar   for   sp   

原文地址:http://www.cnblogs.com/yangsc/p/4027416.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!