LeetCode OJ - Merge Sorted Array

原地归并。

下面是AC代码:

 1  public void merge(int A[], int m, int B[], int n) {
 2         
 3          int len = A.length;
 4          //first copy m elements of A to the end of A
 5          for(int i=m-1,j = len-1;i>=0;i--){
 6              A[j--] = A[i];
 7          }
 8          //merge the A and B
 9          int startA = len - m;
10          int startB = 0;
11          int i = 0;
12          while(startA<len || startB<n){
13              while(startA<len&& startB<n && A[startA]<=B[startB])
14              {
15                  A[i++] = A[startA];
16                  startA++;
17              }
18              while(startA<len && startB<n && B[startB]<A[startA]){
19                  A[i++] = B[startB];
20                  startB++;
21              }
22              while(startA == len && startB<n){
23                  A[i++] = B[startB++];
24              }
25              while(startB == n  && startA<len){
26                  A[i++] = A[startA++];
27              }
28          }
29      }

 

 1 /**
 2       * second method very nice . from the end to start
 3       * @param A
 4       * @param m
 5       * @param B
 6       * @param n
 7       */
 8      public void merge2(int A[], int m, int B[], int n){
 9          int i = m+n-1;
10          while(i>=0 &&( n>=0 || m>=0)){
11              A[i--] = m-1 < 0? B[(n--)-1]:
12                  n-1 < 0? A[(m--)-1] : A[m-1]>=B[n-1]? A[(m--)-1]:B[(n--)-1];
13          }
14      }

 

转载于:https://www.cnblogs.com/echoht/p/3717953.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值