您的位置:首页 > 大数据 > 人工智能

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()

/**
* 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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: