Number of Airplanes in The Sky

题目:

Given an interval list which are flying and landing time of the flight. How many airplanes are on the sky at most?

If landing and flying happens at the same time, we consider landing should happen at first.

For interval list
[
  [1,10],
  [2,3],
  [5,8],
  [4,7]
]
Return 3

分析:

不得不说是扫描线法的思维,把n长度的interval化为2n长度的point set,每个point包括时间和类型(起飞或者降落),然后只要先排序,再按顺序加减就行。
但是tmd这C++真的好坑,为啥没有int类型的comparator!以后千万记得,C++用bool来compare,java用int来compare

解法:

class PointI {
public:    
    int time;
    int flag;
    PointI(int time, int flag) {
        this->time = time;
        this->flag = flag;
    }
};

class Solution {
public:
    /**
     * @param intervals: An interval array
     * @return: Count of airplanes are in the sky.
     */
    static bool compare(const PointI &a, const PointI &b) {
        if (a.time == b.time) {
            return a.flag < b.flag;
        }
        return a.time < b.time;
    }

    int countOfAirplanes(vector<Interval> &airplanes) {
        // write your code here
        int n = airplanes.size();
        vector<PointI> list;
        for (int i = 0; i < n; i++) {
            list.push_back(PointI(airplanes[i].start, 1) );
            list.push_back(PointI(airplanes[i].end, 0) );
        }

        sort(list.begin(), list.end(), compare);
        int res = 0;
        int temp = 0;
        for (int i = 0; i < list.size(); i++) {
            if (list[i].flag == 1) {
                temp++;
            } else {
                temp--;
            }
            res = max(res, temp);
        }
        return res;
    }
};

results matching ""

    No results matching ""