leetcode -- Merge Sorted Array

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 to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.

从后往前遍历,减少移动次数。此题与替换字符串类似

 1 public void merge(int A[], int m, int B[], int n) {
 2         // Start typing your Java solution below
 3         // DO NOT write main() function
 4         int k = m + n - 1;
 5         int aIdx = m - 1, bIdx = n - 1;
 6         while(aIdx >= 0 && bIdx >= 0){
 7             if(A[aIdx] >= B[bIdx]){
 8                 A[k] = A[aIdx];
 9                 aIdx --;
10             } else {
11                 A[k] = B[bIdx];
12                 bIdx --;
13             }
14             k --;
15         }
16         
17         while(bIdx >= 0){
18             A[k] = B[bIdx];
19             bIdx --;
20             k --;
21         }
22     }

 

 

posted @ 2013-08-05 20:54  feiling  阅读(184)  评论(0编辑  收藏  举报