Leetcode 第36场双周赛
记录每个的车位
当请求停车的时候减去
class ParkingSystem {
public:
map<int, int> mp;
ParkingSystem(int big, int medium, int small ) {
mp.clear();
mp[1] = big;
mp[2]=medium;
mp[3]=small;
}
bool addCar(int c) {
if(mp[c]>0){
mp[c]-=1;
return true;
}
return false;
}
};
/**
* Your ParkingSystem object will be instantiated and called as such:
* ParkingSystem* obj = new ParkingSystem(big, medium, small);
* bool param_1 = obj->addCar(carType);
*/
- 1 <= keyName.length, keyTime.length <= 105
- keyName.length == keyTime.length
- keyTime 格式为 "HH:MM" 。
- 保证 [keyName[i], keyTime[i]] 形成的二元对 互不相同 。
- 1 <= keyName[i].length <= 10
- keyName[i] 只包含小写英文字母
利用map分组之后
对每个组内的时间排序来判断
class Solution {
public:
int convert(string s){
return 60*((s[0]-'0')*10+s[1]-'0')+(s[3]-'0')*10+s[4]-'0';
}
vector<string> alertNames(vector<string>& keyName, vector<string>& keyTime) {
// set<string> res;
vector<string> ans;
map<string, vector<int> > mp;
for(int i=0; i<keyName.size(); i++){
mp[keyName[i]].push_back(convert(keyTime[i]));
}
for(auto e:mp){
vector<int>& t = e.second;
sort(t.begin(), t.end());
for(int i=0; i<t.size(); i++){
auto pos = upper_bound(t.begin(), t.end(), t[i]+60);
if(distance(t.begin()+i, pos)>=3){
ans.push_back(e.first);
break;
}
}
}
return ans;
}
};
注意到的是,对于矩阵的一个位置 ans[i][j]
这个数加上K也就是使得rowSum[i]和colSum[j]加上K
那么体现在从0开始的时候,也就是使得rowSum[i]和colSum[j]不小于0
那么从上往下直接取min(rowSum[i], colSum[j])即可
class Solution {
public:
vector<vector<int>> restoreMatrix(vector<int>& rowSum, vector<int>& colSum) {
int n = rowSum.size();
int m = colSum.size();
vector<vector<int> > ans(n, vector<int> (m,0));
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
ans[i][j] = min(rowSum[i], colSum[j]);
rowSum[i] -= ans[i][j];
colSum[j] -= ans[i][j];
}
}
return ans;
}
};
利用map和set的有序
分别记录可用和终止时间
同时利用set的lower_bound函数来二分查找
class Solution {
public:
vector<int> busiestServers(int k, vector<int>& arrival, vector<int>& load) {
vector<int> ans;
map<int, vector<int> > used;
map<int, int> cnt;
int ma = 0;
set<int> use;
for(int i=0; i<k; i++){
use.insert(i);
}
for(int i=0; i<arrival.size(); i++){
int e = arrival[i];
for(auto iter = used.begin(); iter != used.end(); )
{
if(iter->first<=e)
{
for(auto gg:iter->second)
use.insert(gg);
used.erase(iter++);
}
else
break;
}
if(use.size()==0)
continue;
auto pos = use.lower_bound(i%k);
if(pos==use.end())
pos = use.begin();
used[load[i]+e].push_back(*pos);
cnt[*pos]++;
ma = max(ma, cnt[*pos]);
use.erase(pos);
}
for(auto e:cnt){
if(e.second==ma)
ans.push_back(e.first);
}
return ans;
}
};
一条有梦想的咸鱼