首页 > 代码库 > LeetCode "Merge Sorted Array"

LeetCode "Merge Sorted Array"

My first reaction: move all A elements back by n positions, and start everything from A[0] and B[0]. But a smarter idea is to start everything from the end :) So no need to move. Just to take care of all cases.

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