思路:
用一个vector记录每个服务器服务了多少个请求
用一个优先队列存储正在工作的服务器(包括了服务器完成任务的结束时间和编号)
用set集合记录空闲的服务器,stl中set特点使不重复且有序,利用这可以快速寻找,时间优化也在此
代码有详细的注解,并且有关的stl的操作也一并附上
priority_queue:
和队列基本操作相同:
- top 访问队头元素
- empty 队列是否为空
- size 返回队列内元素个数
- push 插入元素到队尾 (并排序)
- emplace 原地构造一个元素并插入队列
- pop 弹出队头元素
- swap 交换内容
priority_queue<Type, Container, Functional>
//升序队列
priority_queue <int,vector<int>,greater<int> > q;
//降序队列
priority_queue <int,vector<int>,less<int> >q;Type为数据类型,Container是容器,Functional理解为按升序还是降序
set: 两个特点:1.有序 2.不重复
begin(); // 返回指向第一个元素的迭代器
end(); // 返回指向迭代器的最末尾处(即最后一个元素的下一个位置)
clear(); // 清除所有元素
count(); // 返回某个值元素的个数
empty(); // 如果集合为空,返回true
equal_range(); //返回集合中与给定值相等的上下限的两个迭代器
erase()–删除集合中的元素
find()–返回一个指向被查找到元素的迭代器
get_allocator()–返回集合的分配器
insert()–在集合中插入元素
lower_bound()–返回指向大于(或等于)某值的第一个元素的迭代器
key_comp()–返回一个用于元素间值比较的函数
max_size()–返回集合能容纳的元素的最大限值
rbegin()–返回指向集合中最后一个元素的反向迭代
rend()–返回指向集合中第一个元素的反向迭代器
size()–集合中元素的数目
swap()–交换两个集合变量
upper_bound()–返回大于某个值元素的迭代器
value_comp()–返回一个用于比较元素间的值的函数
class Solution {
public:
vector<int> busiestServers(int k, vector<int>& arrival, vector<int>& load){
vector<int> count(k, 0); //记录服务了多少个请求
int nowtime=0;//现在的时间 即当前任务开始的时间
int size=arrival.size();
//记录在工作的服务器 pair的first是记录服务器的结束时间 second 记录服务器的编号
priority_queue< pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>> > busy;
set<int> free;//记录空闲的服务器
for(int i=0;i<k;i++) free.insert(i);//刚开始每个服务器都是空闲的
for(int i=0;i<size;i++){
nowtime=arrival[i];//每个请求的开始时间
//先释放完成请求服务器
while(!busy.empty()&&busy.top().first<=nowtime){
free.insert(busy.top().second);//释放该服务器到set集合
busy.pop();//再把这个弹出
}
if(free.empty()) continue;//free空了表示所有的服务器都在忙 则跳过
//再寻找空闲服务器 优化再这里 节省了去寻找下一个空闲服务器的时间
auto temp=free.lower_bound(i%k);//返回大于或等于i%k的第一个元素的迭代器,所以用auto
if(temp==free.end()) temp=free.lower_bound(0); //到头了
busy.push(make_pair(nowtime+load[i],*temp));//first是结束时间 second是编号 使他进入忙的状态
count[*temp]++;
free.erase(temp);//删除集合中的元素
}
int max_times= *max_element(count.begin(),count.end());
vector<int> res;
for(int i=0;i<k;i++)
if(count[i]==max_times) res.push_back(i);
return res;
}
};