zoukankan      html  css  js  c++  java
  • LintCode 6.合并排序数组 ||

    import org.junit.Test;
    
    import java.util.Arrays;
    
    public class MergeSort {
        /**
         * @param A: sorted integer array A
         * @param B: sorted integer array B
         * @return: A new sorted integer array
         * <p>
         * 合并排序数组 II
         * 合并两个排序的整数数组A和B变成一个新的数组。
         * <p>
         * 样例
         * 给出A=[1,2,3,4],B=[2,4,5,6],返回 [1,2,2,3,4,4,5,6]
         * <p>
         * 挑战
         * 你能否优化你的算法,如果其中一个数组很大而另一个数组很小?
         */
        public int[] mergeSortedArray(int[] A, int[] B) {
            // write your code here
            int i = A.length;
            int j = B.length;
            int x = 0;
            int y = 0;
            int[] C = new int[i + j];
            int k = 0;
    
            while (x < i && y < j) {
                if (A[x] <= B[y]) {
                    C[k++] = A[x++];
                } else {
                    C[k++] = B[y++];
                }
            }
    
            while (x < i) {
                C[k++] = A[x++];
            }
            while (y < j) {
                C[k++] = B[y++];
            }
            return C;
        }
    
        @Test
        public void testMergeSortedArray() {
            int[] A = {23, 4, 2, 34, 2, 34, 32};
            int[] B = {6, 245, 3, 234, 2, 46, 23, 45, 23423, 3, 4, 23};
            System.out.println(Arrays.toString(A));
            System.out.println(Arrays.toString(B));
            System.out.println(Arrays.toString(mergeSortedArray(A, B)));
        }
    }
    
  • 相关阅读:
    HDU 4814
    POJ 3415
    HDU 4941
    C scanf()
    hdu 4850 Wow! Such String!
    HDU 4828 Grids
    HDU 4832 Chess
    HDU 4831
    SpringCloud 网飞系 转换阿里系2
    用jianmu建木自动化打包vue前端应用,并远程ssh建立文件夹,scp文件至对应目录
  • 原文地址:https://www.cnblogs.com/wei1/p/9582062.html
Copyright © 2011-2022 走看看