首页 > 其他 > 详细

LeetCode "Merge Sorted Array"

时间:2014-07-22 00:34:07      阅读:366      评论:0      收藏:0      [点我收藏+]

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;
         }
     }
 };

LeetCode "Merge Sorted Array",布布扣,bubuko.com

LeetCode "Merge Sorted Array"

原文:http://www.cnblogs.com/tonix/p/3857891.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!