一道中等题,由于n很大,不能直接用数组模拟,可以用哈希表记录被预定的行,没有被预定的行固定可以做两个小组。
1386. 安排电影院座位
思路
可以看到只有2 - 9号位置的预定状态才会影响结果,因此对于预定的行,只需要记录这8个位置的预定情况即可,可以使用一个8位的整数记录,然后查看低四位,中间四位,高四位是否全为0判断能否做下一组。
复杂度
只需要遍历一次预定数组得到全部的预定状态,对每个状态求能安排的组数是O(1)的,整体复杂度为O(n)
代码
int get(int x)
{
int mask = 0xf;
if((x & mask) == 0)
return 1;
x >>= 2;
if((x & mask) == 0)
return 1;
x >>= 2;
return x == 0;
}
class Solution {
public:
int maxNumberOfFamilies(int n, vector<vector<int>>& reservedSeats) {
unordered_map<int, int> mmap;
vector<int> a;
int index = 0;
for(auto &seats : reservedSeats)
{
int line = seats[0], seat = seats[1];
if(seat == 1 || seat == 10)
continue;
seat -= 2;
if(mmap.contains(line))
{
int i = mmap[line];
int mask = 1 << seat;
a[i] ^= mask;
}
else
{
mmap[line] = index ++;
int mask = 1 << seat;
a.push_back(mask);
}
}
int ans = 2 * (n - index);
for(int i = 0; i < index; i ++)
{
ans += get(a[i]);
}
return ans;
}
};