读书人

Merge Sorted Array (LeetCode) 合拢数

发布时间: 2013-10-02 13:10:38 作者: rapoo

Merge Sorted Array (LeetCode) 合并数组

description:

Given two sorted integer arrays A and B, merge B into A as one sorted array.

Note:
You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.

code:

class Solution {public:    void merge(int A[], int m, int B[], int n) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int *c = new int[m+n];        int *pa=A,*pb=B;        int cnt=0;        while(pa< A+m && pb< B+n)        {            if(*pa < *pb)            {                c[cnt++] = *pa;                pa++;            }            else             {                c[cnt++] = *pb;                pb++;            }        }        while(pa< A+m)        {            c[cnt++] = *pa++;        }        while(pb <B+n)        {            c[cnt++] = *pb++;        }        memcpy(A,c,sizeof(int)*(m+n));    }};


读书人网 >互联网

热点推荐