lintcode-【中等】数飞机

题目:

给出飞机的起飞和降落时间的列表,用 interval 序列表示. 请计算出天上同时最多有多少架飞机?

样例:

对于每架飞机的起降时间列表:[[1,10],[2,3],[5,8],[4,7]], 返回3

答案:

将时间单独取出来,并用一个标记标记其是start还是end,对所有时间按从小到大的顺序排序,如果是start则递增计数器,如果是end则递减计数器。

注意排序时,如果时间相同,而标记不同,则将标记为end的时间排在前面。

代码:

/**
 * Definition of Interval:
 * classs Interval {
 *     int start, end;
 *     Interval(int start, int end) {
 *         this->start = start;
 *         this->end = end;
 *     }
 */
 
#include <algorithm>

using std::sort;

class IntervalPoint
{
public:
    int time;
    int flag;//0表示start时间,1表示end时间
    IntervalPoint(int t, int f)
    {
        time = t;
        flag = f;
    }
};

bool cmp(const IntervalPoint& a, const IntervalPoint& b)
{
    if(a.time == b.time)
    {
        return b.flag < a.flag;
    }
    
    return a.time < b.time;
}

class Solution {
public:
    /**
     * @param intervals: An interval array
     * @return: Count of airplanes are in the sky.
     */
    int countOfAirplanes(vector<Interval> &airplanes) {
        // write your code here
        if(airplanes.empty())
        {
            return 0;
        }
        
        vector<IntervalPoint> points;
        vector<Interval>::iterator beg;
        for(beg = airplanes.begin(); beg != airplanes.end(); ++ beg)
        {
            points.push_back(IntervalPoint(beg->start,0));
            points.push_back(IntervalPoint(beg->end,1));
        }
        
        sort(points.begin(), points.end(), cmp);
        
        int ans = 0;
        int count = 0;
        vector<IntervalPoint>::iterator pointsBeg;
        for(pointsBeg = points.begin(); pointsBeg != points.end(); ++ pointsBeg)
        {
            if(pointsBeg->flag == 0)
            {
                count ++;
            }else
            {
                count --;
            }
            
            ans = (ans > count ? ans : count);
        }
        
        return ans;
    }
};
View Code
原文地址:https://www.cnblogs.com/Shirlies/p/5219724.html