2023-07-18 Leetcode 1851 包含每个查询的最小区间

64 阅读1分钟

Problem: 1851. 包含每个查询的最小区间

思路

有序性 能减少很多重复计算

解题方法

先对查询和区间都进行排序,然后借助优先队列来帮助维护区间

Code


class Solution {
    public int[] minInterval(int[][] intervals, int[] queries) {
        int n = intervals.length;
        int m = queries.length;

        Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
        int[][] qs = new int[m][0];
        for (int i = 0; i < m; i++) {
            qs[i] = new int[]{queries[i], i};
        }

        Arrays.sort(qs, (a, b) -> a[0] - b[0]);
        
        int[] ans = new int[m];
        Arrays.fill(ans, -1);

        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
        int i = 0;
        for (int[] q : qs) {
            while (i < n && intervals[i][0] <= q[0]) {
                int a = intervals[i][0], b = intervals[i][1];
                pq.offer(new int[] {b - a + 1, b});
                ++i;
            }
            while (!pq.isEmpty() && pq.peek()[1] < q[0]) {
                pq.poll();
            }
            if (!pq.isEmpty()) {
                ans[q[1]] = pq.peek()[0];
            }
        }
        return ans;
    }
}