[leetcode] 1386. Cinema Seat Allocation

Description

在这里插入图片描述

A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above.

Given the array reservedSeats containing the numbers of seats already reserved, for example, reservedSeats[i] = [3,8] means the seat located in row 3 and labelled with 8 is already reserved.

Return the maximum number of four-person groups you can assign on the cinema seats. A four-person group occupies four adjacent seats in one single row. Seats across an aisle (such as [3,3] and [3,4]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side.

Example 1:

Input: n = 3, reservedSeats = [[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]]
Output: 4
Explanation: The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group.

Example 2:

Input: n = 2, reservedSeats = [[2,1],[1,8],[2,6]]
Output: 2

Example 3:

Input: n = 4, reservedSeats = [[4,3],[1,4],[4,6],[1,7]]
Output: 4

Constraints:

  • 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
  • All reservedSeats[i] are distinct.

分析

题目的意思是:给定一个电影院的场地,每行10个座位,要求找出4个连续座位的个数,其中走廊两边一边两个也算是相邻。我一开始觉得这个算法没法做了,后面发现别人的做法挺好,每行10个座位,所以能够列举出来每行连续4个座位的情况,然后判断是否属于这几种情况就行了。满足条件的座位序号为:

f1=[2,3,4,5]
f2=[4,5,6,7]
f3=[6,7,8,9]

然后用一个字典统计每行的座位占用情况,最后遍历字典是否满足上面三种情况就知道有多少种连续4个座位相邻的情况,最后字典不包括某一行没有座位占用的情况,因此需要加上这种情况。

remain=(n-len(d))*2

代码

class Solution:
    def maxNumberOfFamilies(self, n: int, reservedSeats: List[List[int]]) -> int:
        d=collections.defaultdict(list)
        f1=[2,3,4,5]
        f2=[4,5,6,7]
        f3=[6,7,8,9]
        for item in reservedSeats:
            d[item[0]].append(item[1])
        res=0
        for v in d.values():
            f=[1,1,1]
            for seat in v:
                if(seat in f1):
                    f[0]=0
                if(seat in f2):
                    f[1]=0
                if(seat in f3):
                    f[2]=0
            if(f[0]==1 or f[2]==1):
                f[1]=0
            res+=sum(f)
        remain=(n-len(d))*2
        return res+remain

参考文献

[LeetCode] Python, hashmap, explained with comments

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值