- Number of Airplanes in the Sky
Given an list interval, which are taking off and landing time of the flight. How many airplanes are there at most at the same time in the sky?
Example
Example 1:
Input: [(1, 10), (2, 3), (5, 8), (4, 7)]
Output: 3
Explanation:
The first airplane takes off at 1 and lands at 10.
The second ariplane takes off at 2 and lands at 3.
The third ariplane takes off at 5 and lands at 8.
The forth ariplane takes off at 4 and lands at 7.
During 5 to 6, there are three airplanes in the sky.
Example 2:
Input: [(1, 2), (2, 3), (3, 4)]
Output: 1
Explanation: Landing happen before taking off.
Notice
If landing and taking off of different planes happen at the same time, we consider landing should happen at first.
思路:
典型的扫描线算法(SweepLine),跟LintCode 599(meeting-room II)一样。
注意:sort的compare必须是struct/class的实例或function,不能只是一个struct/class的名字。
代码如下:
/**
* Definition of Interval:
* classs Interval {
* int start, end;
* Interval(int start, int end) {
* this->start = start;
* this->end = end;
* }
* }
*/
struct event {
int eventTime;
int eventType;
event(int ti, int ty) : eventTime(ti), eventType(ty) {}
};
struct cmp{
bool operator() (event & a, event & b) {
if (a.eventTime < b.eventTime) {
return true;
} else if (a.eventTime == b.eventTime) {
return a.eventType > b.eventType;
} else {
return false;
}
}
} compare;
class Solution {
public:
/**
* @param airplanes: An interval array
* @return: Count of airplanes are in the sky.
*/
int countOfAirplanes(vector<Interval> &airplanes) {
int count = 0, maxCount = 0;
int len1 = airplanes.size();
vector<event> events;
for (int i = 0; i < len1; ++i) {
events.push_back(event(airplanes[i].start, 0));
events.push_back(event(airplanes[i].end, 1));
}
sort(events.begin(), events.end(), compare);
int len2 = events.size();
for (int i = 0; i < len2; ++i) {
if (events[i].eventType == 0) {
count++;
maxCount = max(maxCount, count);
}
else count--;
}
return maxCount;
}
};