算法:两个有序数组的合并

来源:互联网 发布:如何做好网络推广工作 编辑:程序博客网 时间:2024/06/01 13:03

LeetCode OJ Problem:Merge Sorted Array

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 (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m andn respectively.

class Solution {public:    void merge(int A[], int m, int B[], int n) {        if(m == 0)        {            while(n)            {                A[n-1] = B[n-1];                n--;            }            return;        }        else if(n == 0)            return;        int index = m+n-1;        while(m && n)        {            if(A[m-1] >= B[n-1])            {                A[index] = A[m-1];                m--;            }            else            {                A[index] = B[n-1];                n--;            }            index--;        }        if(m == 0)        {            while(n)            {                A[index] = B[n-1];                n--;                index--;            }        }    }};


0 0