You are given a 2D integer array intervals where intervals[i] = [lefti, righti] represents the inclusive interval [lefti, righti].
You have to divide the intervals into one or more groups such that each interval is in exactly one group, and no two intervals that are in the same group intersect each other.
Return the minimum number of groups you need to make.
Two intervals intersect if there is at least one common number between them. For example, the intervals [1, 5] and [5, 8] intersect.
Example 1:
Input: intervals = [[5,10],[6,8],[1,5],[2,3],[1,10]]
Output: 3
Explanation: We can divide the intervals into the following groups:
- Group 1: [1, 5], [6, 8].
- Group 2: [2, 3], [5, 10].
- Group 3: [1, 10].
It can be proven that it is not possible to divide the intervals into fewer than 3 groups.
Example 2:
Input: intervals = [[1,3],[5,6],[8,10],[11,13]]
Output: 1
Explanation: None of the intervals overlap, so we can put all of them in one group.
Constraints:
- 1 <= intervals.length <= 105
- intervals[i].length == 2
- 1 <= lefti <= righti <= 106
首先将 intervals 根据 start 进行排序, 然后用一个 min heap 来保存当前的所有的 group 的 end 值, 每次从 intervals 中拿取一个 interval, 将 interval[0]与 heap 中最小的 end 进行对比, 如果 interval[0] > min_end, 则证明可以放到该组中, 我们将 min_end 从 heap 中取出, 然后放入 interval[1], 完成对该组 end 值的更新。如果 interval[0] <= min_end, 则证明当前 interval[0]小于所有 group 的 end, 也就只能新建一个 group, 这时我们只将 interval[1]放到 heap 中。
use std::cmp::Reverse;
use std::collections::BinaryHeap;
impl Solution {
pub fn min_groups(mut intervals: Vec<Vec<i32>>) -> i32 {
intervals.sort_by(|l1, l2| l1[0].cmp(&l2[0]));
let mut heap = BinaryHeap::new();
for itv in intervals {
if let Some(Reverse(end)) = heap.pop() {
if itv[0] > end {
heap.push(Reverse(itv[1]));
continue;
}
heap.push(Reverse(end));
}
heap.push(Reverse(itv[1]));
}
heap.len() as i32
}
}

403

被折叠的 条评论
为什么被折叠?



