Merge Sorted Array

来源:互联网 发布:淘宝苏宁易购怎么退货 编辑:程序博客网 时间:2024/06/05 06:29

Merge Sorted Array

 Total Accepted: 6782 Total Submissions: 21148My Submissions

Given two sorted integer arrays A and B, merge B into A as one sorted array.

Note:
You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.




    public static void merge2(int[] A, int m, int[] B, int n) {        int i = m + n - 1;        m--;n--;        while (m >= 0 && n >= 0) A[i--] = A[m] > B[n] ? A[m--] : B[n--];        while (n >= 0) A[i--] = B[n--];    }

或者:

public static void merge(int[] A, int m, int[] B, int n) {        System.arraycopy(A, 0, A, n, m);        int a = n, b = 0, i = 0;        while (a < m + n && b < n) A[i++] = A[a] <= B[b] ? A[a++] : B[b++];        while (b < n) A[i++] = B[b++];    }


0 0