1. 程式人生 > >[LeetCode]632. Smallest Range

[LeetCode]632. Smallest Range

給k個遞增陣列,找出一個最小範圍,保證每個陣列內至少有一個數字落在這個區間上

類似歸併排序思想——多維有序陣列問題考慮mergeSort+pq思想

pq內每次poll出當前最小值,max儲存當前已訪問的最大值,當前pq中的所有值一定在這個區間內(滿足該區間覆蓋所有陣列條件),只要看這個區間是否為更小的那個區間即可

public class Solution {
    public int[] smallestRange(List<List<Integer>> nums) {
        int start = -1;
        int end = -1;
        int max = Integer.MIN_VALUE;
        int range = Integer.MAX_VALUE;
        PriorityQueue<Element> queue = new PriorityQueue(new Comparator<Element>() {
            public int compare(Element e1, Element e2) {
                return e1.val - e2.val;
            }
        });
        for (int i = 0; i < nums.size(); i++) {
            Element e = new Element(nums.get(i).get(0), 0, i);
            queue.offer(e);
            max = Math.max(max, e.val);
        }
        while (queue.size() == nums.size()) {
            Element e = queue.poll();
            if (max - e.val < range) {
                range = max - e.val;
                start = e.val;
                end = max;
            }
            if (e.index + 1 < nums.get(e.row).size()) {
                e.index = e.index + 1;
                e.val = nums.get(e.row).get(e.index);
                queue.offer(e);
                if (e.val > max) {
                    max = e.val;
                }
            }
        }
        return new int[]{start, end};
    }
    class Element {
        int index;
        int row;
        int val;
        public Element(int val, int index, int row) {
            this.val = val;
            this.index = index;
            this.row = row;
        }
    }
}