Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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;
         }
     }
 };
posted on 2014-07-21 10:18  Tonix  阅读(129)  评论(0编辑  收藏  举报