[LintCode] Merge Sorted Array II

373 查看

Problem

Merge two given sorted integer array A and B into a new sorted integer array.

Example

A=[1,2,3,4]

B=[2,4,5,6]

return [1,2,2,3,4,4,5,6]

Note

循环里最好先考虑A和B其中之一已经处理完的情况,就直接顺序放另一个没处理完的即可。然后再在else里展开方法。
避免其中一个数组较小会浪费效率的情况。

Solution

class Solution {
    public ArrayList<Integer> mergeSortedArray(ArrayList<Integer> A, ArrayList<Integer> B) {
        // write your code here
        int lena = A.size();
        int lenb = B.size();
        ArrayList<Integer> C = new ArrayList<Integer>();
        int i = 0, j = 0;
        while (i + j < lena + lenb) {
            if (i == lena) {
                C.add(B.get(j));
                j++;
            }
            else if (j == lenb) {
                C.add(A.get(i));
                i++;
            }
            else {
                if (A.get(i) >= B.get(j)) {
                    C.add(B.get(j));
                    j++;
                }
                else {
                    C.add(A.get(i));
                    i++;
                }
            }
        }
        return C;
    }
}

丫把参数又换成int[]了。。。

class Solution {
    public int[] mergeSortedArray(int[] A, int[] B) {
        // Write your code here
        int lena = A.length;
        int lenb = B.length;
        int[] C = new int[lena + lenb];
        int i = 0, j = 0;
        for (int k = 0; k < lena + lenb; k++) {
            if (i == lena) {
                C[k] = B[j];
                j++;
            }
            else if (j == lenb) {
                C[k] = A[i];
                i++;
            }
            else {
                if (A[i] < B[j]) {
                    C[k] = A[i];
                    i++;
                }
                else {
                    C[k] = B[j];
                    j++;
                }
            }
        }
        return C;
    }
}