leetcode merge sorted array

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 nrespectively.

A有m个值,条件已经假设了A的大小 >= m+n,A是融合后的数组。

用辅助list方式:

    public void merge(int A[], int m, int B[], int n) {
      //  if (A.length == 0 || B.length == 0 || A.length < m + n) {
      //      return;
      //  }
        ArrayList <Integer> s = new ArrayList<Integer>();
        int i = 0,j = 0;

        for (; i < m && j < n; ) {
            if (A[i] <= B[j]){
                s.add(A[i]);
                i++;
            }else {
                s.add(B[j]);
                j++;
            }
        }
        while (i < m) s.add(A[i++]);
        while (j < n) s.add(B[j++]);

        for (int k = 0; k < s.size(); k++) {
            A[k] = s.get(k);
        }
    }

 

不用辅助list方式,因为A一定有足够空间,A和B是已经排好序的数组,那么可以从后向前比较并存储:

    public void merge2(int A[], int m, int B[], int n) {
        for (int idx = m + n - 1; idx >= 0; idx--) {
            if (m <= 0) {
                A[idx] = B[--n];
            } else if (n <= 0) {
                break;
            } else if (A[m-1] < B[n-1]) {
                A[idx] = B[--n];
            } else {
                A[idx] = A[--m];
            }
        }
    }
Tagged on: , ,

发表评论

电子邮件地址不会被公开。 必填项已用*标注

This site uses Akismet to reduce spam. Learn how your comment data is processed.