https://zhuanlan.zhihu.com/p/26657786
https://www.quora.com/What-is-the-problem-if-we-sort-the-intervals-according-to-their-finishing-time-like-the-interval-scheduling-problem-Why-is-it-necessary-to-sort-according-to-the-starting-time-in-the-interval-partitioning-problem
第一,排序。在一般情况下,按照interval的start升序排序,在必要情况下,对于start相同的interval,按照interval的end的降序排序。
第二,greedy。有时候是两个interval之间的greedy,有时候是一群interval之间的greedy。
第三,map。c++里的map,是用红黑树实现的,这里为了方便就叫map。当前两板斧都无法奏效的时候,可以试试这个。
然而排序常常和greedy一起使用。先排序,再greedy,是对付interval最常见的解法。当然这种套路远不仅限于interval类的题目。一个简单的题目是Leetcode 56. Merge Intervals.
Given a collection of intervals, merge all overlapping intervals. For example, Given [1,3],[2,6],[8,10],[15,18], return [1,6],[8,10],[15,18].
在排序之后,我们遍历数组,当两个interval有overlap的时候,我们取最小的start和最大的end。因为排序的结果,最小的start一定更早出现,所以我们只需要贪婪地去取最大的end就可以了。来看一下代码。
vector<Interval> merge(vector<Interval>& ins) {
if (ins.empty()) return vector<Interval>{};
sort(ins.begin(), ins.end(), [](const Interval & a, const Interval & b) -> bool{ return a.start < b.start; });
vector<Interval> res {ins[0]};
for (int i = 1; i < ins.size(); ++i) {
if (res.back().end < ins[i].start) res.push_back(ins[i]);
else res.back().end = max(res.back().end, ins[i].end);
}
return res;
}
But I think what you mean is, why can't we sort on finishing time and then process the intervals from first to last, like in interval scheduling? And I think the reason is, for interval partitioning you need to keep track of which processes are currently running, or else you don't know which resources are free. So you need to know when they start to be able to account for that.
But for interval scheduling you actually don't need to know which processes are currently running. When a process finishes you can easily check whether the resource would have been available or not, and if it was, then clearly it should have processed that interval, so we can count it.