LintCode: Number of Airplanes in the Sky
2016-01-07 13:12
483 查看
C++
(1)把interval数组中的所有start和所有end放在同一个数组中,然后进行排序,遇到start就起飞一架飞机,遇到一架end就降落一架飞机,所以start有个+1属性,end有个-1属性,这样就可以根据排序之后的数组得知任意时间飞行中的飞机的数量了
(2)pair,make_pair,val.first,val.second
(3)sort(), max()
(4)for (auto &i : Object) {}
(5)push_back()
另一个解法(无需排序):
刚开始阅读题目的时候,我以为起飞时间和降落时间都是0~24之内,所以就用了两个长度30的辅助数组,这种方法可以避免排序。
但是,无法AC,因为interval中的元素,最大的有几十万,如果辅助数组也这么大的话,那很容易超时。
(1)把interval数组中的所有start和所有end放在同一个数组中,然后进行排序,遇到start就起飞一架飞机,遇到一架end就降落一架飞机,所以start有个+1属性,end有个-1属性,这样就可以根据排序之后的数组得知任意时间飞行中的飞机的数量了
(2)pair,make_pair,val.first,val.second
(3)sort(), max()
(4)for (auto &i : Object) {}
(5)push_back()
/** * Definition of Interval: * classs Interval { * int start, end; * Interval(int start, int end) { * this->start = start; * this->end = end; * } */ 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 vector<pair<int, int> > v; for (auto &i : airplanes) { v.push_back(make_pair(i.start, 1)); v.push_back(make_pair(i.end, -1)); } int cnt = 0, res = 0; sort(v.begin(), v.end()); for (auto &i : v) { cnt += i.second; res = max(cnt, res); } return res; } };
另一个解法(无需排序):
刚开始阅读题目的时候,我以为起飞时间和降落时间都是0~24之内,所以就用了两个长度30的辅助数组,这种方法可以避免排序。
但是,无法AC,因为interval中的元素,最大的有几十万,如果辅助数组也这么大的话,那很容易超时。
/** * Definition of Interval: * classs Interval { * int start, end; * Interval(int start, int end) { * this->start = start; * this->end = end; * } */ 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 int fly[30] = {0}; int land[30] = {0}; int len = airplanes.size(); for (int i = 0; i < len; i++ ) { fly[airplanes[i].start] ++; land[airplanes[i].end] --; } int max = 0, cur = 0; for (int i = 0; i < 30; i++ ) { cur = cur + fly[i] + land[i]; if (cur > max) { max = cur; } } return max; } };
相关文章推荐
- [已解决]使用matplotlib生成jpg报错:encoder jpeg not available
- 处于CLOSE_WAIT和TIME_WAIT状态连接的原因及解决
- Baidu地图的相关开发经验
- Communications link failure
- YTU 1007: Redraiment猜想
- 解决has leaked ServiceConnection com.baidu.location.c@427b6780
- 实现Gmail邮箱翻转效果之ActionBar
- YTU 1003: Redraiment的遭遇
- 实现Gmail邮箱翻转效果之翻转动画
- 实现Gmail邮箱翻转效果之开篇
- 在selenium测试中使用XPATH功能函数starts-with、contains、descendant、ancestor、text()定位网页元素
- 用 map 输出一定格式的字符串Plain=w=b~|~t=e~|~e=c~|~r=d~|~q=a
- Saltstack的grains组件(5)
- 新款Macbook Air安装Windows8.1黑屏解决教程
- [王垠系列]Braid - 一个发人深思的游戏
- 摘花生 http://bailian.openjudge.cn/summeracm2014final/L/
- POJ 2010 Moo University - Financial Aid(优先队列or二分搜索—最大化K大值)
- rails手脚架(scaffold)功能
- Failed to set permissions of path
- MFC的OnPaint工作原理