[LintCode] 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?

Example

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

Note

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

http://www.lintcode.com/en/problem/number-of-airplanes-in-the-sky/

將所有區間的start與end放在一起排序,但是要標記其是屬性,然后統一排序,問題就轉化成了括號匹配嵌套的問題了(最大有多少層括號嵌套,比如說((()))就是一個3層嵌套,()(()))最大嵌套是2),這里start相當於左括號,end相當於右括號,只要用一個cnt來記錄,遇到start就加1,遇到end就減1,記錄過程中的最大值就是答案。 

 1 /**
 2  * Definition of Interval:
 3  * classs Interval {
 4  *     int start, end;
 5  *     Interval(int start, int end) {
 6  *         this->start = start;
 7  *         this->end = end;
 8  *     }
 9  */
10 class Solution {
11 public:
12     /**
13      * @param intervals: An interval array
14      * @return: Count of airplanes are in the sky.
15      */
16     int countOfAirplanes(vector<Interval> &airplanes) {
17         // write your code here
18         vector<pair<int, bool> > v;
19         for (auto &i : airplanes) {
20             v.push_back(make_pair(i.start, true));
21             v.push_back(make_pair(i.end, false));
22         }
23         int cnt = 0, res = 0;
24         sort(v.begin(), v.end());
25         for (auto &i : v) {
26             if (i.second) ++cnt;
27             else --cnt;
28             res = max(cnt, res);
29         }
30         return res;
31     }
32 };

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM