[LeetCode]Merge Sorted Array

来源:互联网 发布:阿里云视频服务器 编辑:程序博客网 时间:2024/06/14 05:39
题意;将A,B连个有序数组合并到A中,A空间充足
思路1: 基本思路很简单,开辟一个额外数组,空间复杂度和时间复杂度都为O(N)
代码1:

public class Solution {    public void merge(int A[], int m, int B[], int n) {        if(n == 0)return;        if(m == 0){            System.arraycopy(B, 0, A, 0, n);            return;        }        int i =0, j=0, temp = 0,k=0;        int [] C = new int[A.length];        while (i < m && j < n){            while (i < m && A[i] <= B[j]){                C[k ++] = A[i ++];            }            while (i < m && j < n && B[j] < A[i]){                C[k ++] = B[j ++];            }        }        if(i < m){            System.arraycopy(A, i, C, k , m - i);        }        if(j < n){            System.arraycopy(B, j, C, k, n - j);        }        System.arraycopy(C, 0, A, 0, C.length);    }}
思路2:从尾部反向遍历,将大的先放入数组的尾部空间复杂度为O(1),时间复杂度为O(N)
代码2:

public class Solution {    public void merge(int A[], int m, int B[], int n) {        if(n == 0)return;        if(m == 0){            System.arraycopy(B, 0, A, 0, n);            return;        }        int tail = m + n-1;        n--;m--;        while (m >= 0 && n >=0){            A[tail --] = Math.max(A[m], B[n]);            if(A[m] >= B[n]) m--;            else n--;        }        //while (n -- > 0){        //    A[tail --] = B[n];        //}        if(n >= 0){            System.arraycopy(B,0,A,0,n+1);        }    }}



1 1