LintCode 391: Number of Airplanes in the Sky (扫描线算法经典题)

  1. 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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值