题目地址:
https://leetcode.com/problems/cinema-seat-allocation/description/
电影院有
n
n
n行,每行
10
10
10个位置,给定若干已经占据的位置,问能安排多少个
4
4
4人组,每个组占据
2345
,
4567
,
6789
2345,4567, 6789
2345,4567,6789之一。
先用位运算表示一下有占据位置的行的情况,然后分情况讨论来累加,最后加上 2 2 2乘以空行的数量。代码如下:
class Solution {
public:
int maxNumberOfFamilies(int n, vector<vector<int>>& v) {
unordered_map<int, int> mp;
for (auto& e : v) mp[e[0]] |= 1 << e[1] - 1;
int res = 0;
const int full = (1 << 4) - 1;
for (auto& [k, x] : mp) {
if (!(x >> 1 & full) && !(x >> 5 & full))
res += 2;
else if (!(x >> 1 & full) || !(x >> 3 & full) || !(x >> 5 & full))
res++;
}
res += 2 * (n - mp.size());
return res;
}
};
时空复杂度 O ( l v ) O(l_v) O(lv)。