# 2、区间分组&小顶堆

# Leetcode 6178. 将区间分为最少组数

import java.util.*;

public class Solution {
    public static void main(String[] args) throws Exception {
        Solution solution = new Solution();
        int[][]intervals = {{5, 10},{5, 10},{5, 10},{5, 10}};
        System.out.println(solution.minGroups(intervals));
    }
    class Edge{
        int l,r;
    }

    public int minGroups(int[][] intervals) {
        //构造小顶堆:
        PriorityQueue<Integer> small_heap=new PriorityQueue<>();
        int n=intervals.length;
        List<Edge> arrayList=new ArrayList<>();
        for (int i = 0; i < n; i++) {
            Edge edge=new Edge();
            edge.l=intervals[i][0];
            edge.r=intervals[i][1];
            arrayList.add(edge);
        }
        arrayList.sort((e1,e2)->e1.l-e2.l);
        for (Edge edge : arrayList) {
            if(small_heap.isEmpty())
                small_heap.offer(edge.r);
            else{
                int value=small_heap.peek();
                if(edge.l<=value){
                    small_heap.offer(edge.r);
                }else{
                    small_heap.remove();
                    small_heap.offer(edge.r);
                }
            }
        }
        return small_heap.size();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40