題目:
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
題解:
這道題是說讓B merge到 A 裡面。
先複習下原本我們在MergeSort裡面怎麼利用一個新建的數量來merge two array:
程式碼如下:
1 public int[] mergeTwoList(int[] A, int[] B) {
2 int[] C = new int[A.length + B.length];
3 int k = 0;
4 int i = 0;
5 int j = 0;
6 while(i < A.length && j < B.length) {
7 if (A[i] < B[j])
8 C[k++] = A[i++];
9 else
10 C[k++] = B[j++];
11 }
12 while (i < A.length)
13 C[k++] = A[i++];
14 while (j < B.length)
15 C[k++] = B[j++];
16 return C;
17 }
2 int[] C = new int[A.length + B.length];
3 int k = 0;
4 int i = 0;
5 int j = 0;
6 while(i < A.length && j < B.length) {
7 if (A[i] < B[j])
8 C[k++] = A[i++];
9 else
10 C[k++] = B[j++];
11 }
12 while (i < A.length)
13 C[k++] = A[i++];
14 while (j < B.length)
15 C[k++] = B[j++];
16 return C;
17 }
然後我們再順便複習下,怎麼merge two linked list,程式碼如下:
1 public ListNode mergeTwoLists(ListNode leftlist, ListNode rightlist){
2 if(rightlist == null)
3 return leftlist;
4 if(leftlist == null)
5 return rightlist;
6
7 ListNode fakehead = new ListNode(-1);
8 ListNode ptr = fakehead;
9 while(rightlist!=null&&leftlist!=null){
10 if(rightlist.val<leftlist.val){
11 ptr.next = rightlist;
12 ptr = ptr.next;
13 rightlist = rightlist.next;
14 }else{
15 ptr.next = leftlist;
16 ptr = ptr.next;
17 leftlist = leftlist.next;
18 }
19 }
20
21 if(rightlist!=null)
22 ptr.next = rightlist;
23 if(leftlist!=null)
24 ptr.next = leftlist;
25
26 return fakehead.next;
27 }
2 if(rightlist == null)
3 return leftlist;
4 if(leftlist == null)
5 return rightlist;
6
7 ListNode fakehead = new ListNode(-1);
8 ListNode ptr = fakehead;
9 while(rightlist!=null&&leftlist!=null){
10 if(rightlist.val<leftlist.val){
11 ptr.next = rightlist;
12 ptr = ptr.next;
13 rightlist = rightlist.next;
14 }else{
15 ptr.next = leftlist;
16 ptr = ptr.next;
17 leftlist = leftlist.next;
18 }
19 }
20
21 if(rightlist!=null)
22 ptr.next = rightlist;
23 if(leftlist!=null)
24 ptr.next = leftlist;
25
26 return fakehead.next;
27 }
可以看出merge的思路都是在從頭比較兩個list的value,用兩個指標分別指向當前要比較的node上面。而且最後都會處理下剩下的元素。
而這道題是不能借助一個新的array的,那麼我們就不好從前往後比了(不好插入位置)。方便的方法是從後往前比,然後最後處理剩下的元素。
程式碼如下:
public void merge(int A[], int m, int B[], int 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] = B[n-1];
n--;
}
}
while(n > 0){
A[m+n-1] = B[n-1];
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] = B[n-1];
n--;
}
}
while(n > 0){
A[m+n-1] = B[n-1];
n--;
}
}