美文网首页
Merge 2 sorted array

Merge 2 sorted array

作者: Star_C | 来源:发表于2018-04-08 00:18 被阅读0次

    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;
        }
    }
    

    相关文章

      网友评论

          本文标题:Merge 2 sorted array

          本文链接:https://www.haomeiwen.com/subject/ojwuhftx.html