这道题能通过的关键在于这个,主要是因为n>>cnt.size();如果你是遍历n,则一定超时,如果遍历的是cnt,则能够成功提交。
res+2*(n-cnt.size());
class Solution {
public:
int func(map<int, int>& blocks){
if (blocks.size()==0){
return 2;
}
// start 2,4,6
int count = 0;
for(int start=2;start<=6;){
if (blocks[start]==1||blocks[start+1]==1){
start += 2;
}
else{
if (blocks[start+2]==1||blocks[start+3]==1){
start += 4;
}
else{
count ++;
start += 4;
}
}
}
return count;
}
//reservedSeats最多10010个
int maxNumberOfFamilies(int n, vector<vector<int>>& reservedSeats) {
map<int, map<int, int>> cnt;
for(int i=0;i<reservedSeats.size();i++){
int row = reservedSeats[i][0];
int colblock = reservedSeats[i][1];
if (cnt.find(row)==cnt.end()){
map<int, int> temp;
temp[colblock] = 1;
cnt[row] = temp;
}
else{
cnt[row][colblock] = 1;
}
}
int res = 0;
for(auto it=cnt.begin();it!=cnt.end();it++){
res += func(it->second);
}
return res+(n-cnt.size())*2;
}
};