Merge 2 sorted array

2018-04-08  本文已影响0人  Star_C

Question

from lintcode
This is a very basic but highly frequently asked question. I have met this question in the university class, interviews and ladder challenges. Why do people like to ask this question so often?

Idea

Well, compare each one from two arrays and push the smaller one into the result array. Repeating this until the end and everything will be done.

public class Solution {
    /**
     * @param A: sorted integer array A
     * @param B: sorted integer array B
     * @return: A new sorted integer array
     */
    public int[] mergeSortedArray(int[] A, int[] B) {
        // write your code here
        int[] result = new int[A.length + B.length];
        int ai = 0, bi = 0, res_i = 0;

        while (ai < A.length && bi < B.length)
            result[res_i++] = A[ai] > B[bi] ? B[bi++] : A[ai++];

        int remain_i = ai < A.length ? ai: bi;
        int[] remain = ai < A.length ? A : B;

        while (remain_i < remain.length)
          result[res_i++] = remain[remain_i++];
        return result;
    }
}
上一篇下一篇

猜你喜欢

热点阅读