如上图所示,电影院的观影厅中有 n 行座位,行编号从 1 到 n ,且每一行内总共有 10 个座位,列编号从 1 到 10 。
给你数组 reservedSeats ,包含所有已经被预约了的座位。比如说,researvedSeats[i]=[3,8] ,它表示第 3 行第 8 个座位被预约了。
请你返回 最多能安排多少个 4 人家庭 。4 人家庭要占据 同一行内连续 的 4 个座位。隔着过道的座位(比方说 [3,3] 和 [3,4])不是连续的座位,但是如果你可以将 4 人家庭拆成过道两边各坐 2 人,这样子是允许的。
示例 1:
输入:n = 3, reservedSeats = [[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]]
输出:4
解释:上图所示是最优的安排方案,总共可以安排 4 个家庭。蓝色的叉表示被预约的座位,橙色的连续座位表示一个 4 人家庭。
示例 2:
输入:n = 2, reservedSeats = [[2,1],[1,8],[2,6]]
输出:2
示例 3:
输入:n = 4, reservedSeats = [[4,3],[1,4],[4,6],[1,7]]
输出:4
提示:
1 <= n <= 10^9
1 <= reservedSeats.length <= min(10*n, 10^4)
reservedSeats[i].length == 2
1 <= reservedSeats[i][0] <= n
1 <= reservedSeats[i][1] <= 10
所有 reservedSeats[i] 都是互不相同的。
通过次数1,517提交次数6,325
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cinema-seat-allocation
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
首先一排座位最多能坐两个家庭,
其次能坐下一个家庭的位置只有 2345, 4567, 6789。
如果 2345, 6789 都为空,则可以坐下两个家庭,
如果 2345, 6789 有一个为空,则可以坐下一个家庭。
所以只要判断每一行 23 45 67 89 的空闲情况,就可以知道这一行能坐几个家庭。
另外需要注意的是此题数据规模很大,如果对于每一行都进行上述判断会超时,
所以我们不妨只判断坐了人的行,没坐人的行直接坐下两个家庭即可。
时间复杂度:O(K), K是reservedSeats的长度
空间复杂度:O(K)
class Solution(object):
def maxNumberOfFamilies(self, n, reservedSeats):
"""
:type n: int
:type reservedSeats: List[List[int]]
:rtype: int
"""
from collections import defaultdict
dic = defaultdict(set)
res = 0
usedrow = set()
for row, seat in reservedSeats:
dic[row].add(seat)
usedrow.add(row)
for row in usedrow:
twothree = 2 not in dic[row] and 3 not in dic[row]
fourfive = 4 not in dic[row] and 5 not in dic[row]
sixseven = 6 not in dic[row] and 7 not in dic[row]
eightnine = 8 not in dic[row] and 9 not in dic[row]
if twothree and fourfive and sixseven and eightnine:
res += 2
elif twothree and fourfive:
res += 1
elif fourfive and sixseven:
res += 1
elif sixseven and eightnine:
res += 1
return res + (n - len(usedrow)) * 2