Merge Sorted Array

来源:互联网 发布:lex js语法解析 编辑:程序博客网 时间:2024/05/19 21:14

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 (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.

    public void merge(int A[], int m, int B[], int n) {

        

    }

分析:

把有序整形数组B全部merge进有序数组A中,并保持新的数组有序,假设A中有足够大的空间。

偷懒解法:

    public void merge(int A[], int m, int B[], int n) {    for(int i =0;i<n;i++){    A[m+i]=B[i];    }    Arrays.sort(A);    }



按照正常思路,应该是新建一个m+n大小的数组,然后依次从AB中取小的那个值,不过对边界判断要注意,容易访问越界。


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


0 0