9.1

You are given two sorted arrays, A and B, and A has a large enough buffer at the end
to hold B. Write a method to merge B into A in sorted order.

First let's take a look at how merge two arrays works in merge sort algorithm;

 
  

public int[] mergeTwoArrays(int[] A, int[] B) {
  int Alength = A.length;
  int Blength = B.length;
  int i = 0;
  int j = 0;
  int k = 0;
  int[] C = new int[Alength + Blength];
    // note integer can not be null; so can not write A[i] != null
  while (i < Alength && j < Blength) {
    if (A[i >= B[j]) {
      C[k++] = B[j++];
    }
    else {
      C[k++] = A[i++];
    }
  }

 
  

  while (i < Alength) {
    C[k++] = A[i++];
  }

  while (j < Blength) {
    C[k++] = B[j++];
  }
  return C;
}

 Next is merge two sorted list

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
  if (l1 == null)
    return l2;
  if (l2 == null)
    return l1;
  ListNode prehead = new ListNode(0);
  // point to record the current position in the result;
  ListNode point = prehead;
  ListNode curr1 = l1;
  ListNode curr2 = l2;
  while (curr1 != null && curr2 != null) {
    if (curr1.val < curr2.val) {
      ListNode temp = curr1.next;
      point.next = curr1;
      point = curr1;
      curr1 = curr1.next;
    }
    else {
      point.next = curr2;
      point = curr2;
      curr2 = curr2.next;
    }
  }

  while (curr1 != null) {
    point.next = curr1;
  }
  while (curr2 != null) {
    point.next = curr2;
  }
  return prehead;
}

Back to this question, it's a special case of merge two sorted array in which array A is much larger than array B. Therefore we don't need extra space to store the merged array. The strategy is to compare from then end to the front.

public void merge(int[] A, int m, int[] B, int n) {
  // two points m and n;
  while (m > 0 && n > 0) {
    if (A[m - 1] < B[n - 1]) {
      A[m + n - 1] = A[m - 1];
      m--;
    }
    else {
      A[m + n - 1] = A[n - 1];
      n--;
    }
  }

  while (n > 0) {
    A[m + n - 1] = A[n - 1];
    n--;
  }
}

 

转载于:https://www.cnblogs.com/xiaotra/p/4094367.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值