Merge Sorted Array——算法练习

来源:互联网 发布:淘宝交易额 英文 编辑:程序博客网 时间:2024/04/30 07:37

Merge two given sorted integer array A and B into a new sorted integer array.
(合并两个排好序的数组)
样例
A=[1,2,3,4]
B=[2,4,5,6]
return [1,2,2,3,4,4,5,6]

挑战 Expand
How can you optimize your algorithm if one array is very large and the other is very small?
(如果一个数据很大,另一个很小,那么如何优化算法)

public ArrayList<Integer> mergeSortedArray(ArrayList<Integer> A,            ArrayList<Integer> B) {        // 给出一中比较常规典型的解法,就是依次比较A,B中的元素,将较小的插入新的数组中,最后将有剩余的数组中的元素全部补在后面        ArrayList<Integer> list = new ArrayList<>();        int i = 0;        int j = 0;        int lenA = A.size();        int lenB = B.size();        while (i < lenA && j < lenB) {            int a = A.get(i);            int b = B.get(j);            if (a < b) {                list.add(a);                i++;            } else {                list.add(b);                j++;            }        }        while (i < lenA) {            list.add(A.get(i++));        }        while (j < lenB) {            list.add(B.get(j++));        }        return list;    }  

【附:开课吧算法讨论组参考答案】
题目的考点有两个:
一是“有序”二字,这个很重要,如果有些童鞋把两个数组放一块然后重新排序一下,那就辜负了“有序”这个条件,这是做题的大忌。
二是其实就是对数组操作的熟练程度,相信有很多童鞋能想到思路,但是写不出基本无bug的代码。所以多练习多写,是必须的!

算法思路如下:
鉴于是有序的,所以我们用两个指针(或者是索引,理解为能找到两个数组元素的东东就可以了),从两个数组头部(或尾部)开始遍历,分别比较两个数组当前的值,把比较小(大)的数,放入指定位置(指定位置就是新数组中该元素应该处于的位置),然后移动指针。

参考代码如下:

public void merge(int A[], int m, int B[], int n) {     int index = m + n;     while (m > 0 && n > 0) {         if (A[m - 1] > B[n - 1]) {             A[--index] = A[--m];         } else {             A[--index] = B[--n];         }     }     while (n > 0) {         A[--index] = B[--n];     } } 
0 0
原创粉丝点击