码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Merge Sorted Array"

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

标签:style   blog   color   os   io   art   

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"

标签:style   blog   color   os   io   art   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!