算法題:合並N個長度為L的有序數組為一個有序數組(JAVA實現)


昨天面試被問到這道算法題,一時沒有回答上來,今天思考了一下,參閱了網上的教程,做了一個JAVA版本的實現。

方案一:

新建一個N*L的數組,將原始數組拼接存放在這個大數組中,再調用Arrays.sort()進行排序,或者使用其它排序方法即可。

此方法時間復雜度為o(N*Llog2N*L);

具體代碼實現如下:

import java.util.Arrays;
class Solution {
    public static int[] MergeArrays(int[][] array) {
        int N = array.length, L;
        if (N == 0)
            return new int[0];
        else {
            L = array[0].length;
            for (int i = 1; i < N; i++)
                if (L != array[i].length)
                    return new int[0];
        }
        int[] result = new int[N * L];
        for (int i = 0; i < N; i++)
            for (int j = 0; j < L; j++)
                result[i * L + j] = array[i][j];
        Arrays.sort(result);
        return result;
    }
}

 

方案二:

使用PriorityQueue實現最小堆,需要定義一個指針數組,用於保存這N個數組的index,定義Node類用於保存當前數值(value)和該數字所在的數組序號(idx),並且覆寫Comparetor<Node>的compare方法實現自定義排序。PriorityQueue的offer()和poll()方法時間復雜度均為logn。

思路:首先將N個數組的第一位放到PriorityQueue,循環取出優先隊列的首位(最小值)放入result數組中,並且插入該首位數字所在數組的下一個數字(如果存在),直到所有數字均被加入到result數組即停止(N*L)次。

時間復雜度:O(N*LlogN)

空間復雜度:O(N)

代碼實現:

import java.util.PriorityQueue;
import java.util.Arrays;
import java.util.Comparator;

public class SortedArraysMerge {
    static class Node {
        int value;
        int idx;

        public Node(int value, int idx) {
            this.value = value;
            this.idx = idx;
        }
    }

    public static int[] MergeArrays(int[][] arr) {
        int N = arr.length, L;
        if (N == 0)//此時傳入數組為空
            return new int[0];
        else {//判斷數組是否符合規范
            L = arr[0].length;
            for (int i = 1; i < N; i++)
                if (arr[i].length != L)
                    return new int[0]; //此時數組不規范
        }
        int[] result = new int[N * L];
        int[] index = new int[N];
        Arrays.fill(index, 0, N, 0);
        PriorityQueue<Node> queue = new PriorityQueue<Node>(new Comparator<Node>() {
            @Override
            public int compare(Node n1, Node n2) {
                if (n1.value < n2.value)
                    return -1;
                else if (n1.value > n2.value)
                    return 1;
                else
                    return 0;
            }
        });
        for (int i = 0; i < N; i++) {
            Node node = new Node(arr[i][index[i]++], i);
            queue.offer(node);
        }
        System.out.println("" + queue.size());
        int idx = 0;
        while (idx < N * L) {
            Node minNode = queue.poll();
            result[idx++] = minNode.value;
            if (index[minNode.idx] < L) {
                queue.offer(new Node(arr[minNode.idx][index[minNode.idx]], minNode.idx));
                index[minNode.idx]++;
            }
        }
        return result;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM