第一种直观的方法,第48个TC超时了。比较暴力的查找两个被预定的座位之间有多少个空位。情况为4<,==4,>4&<8,==8,==9,==10。其中等于4要判断下是不是有一个座位被过道隔开,同样,等于8的时候也需要作同样的判断。
class Solution:
def maxNumberOfFamilies(self, n: int, reservedSeats: List[List[int]]) -> int:
reservedSeats.sort(key = lambda x: (x[0],x[1]))
print(reservedSeats)
dic = collections.defaultdict(list)
for row, column in reservedSeats:
dic[row].append(column)
res = 0
for row in range(1, n+1):
if row not in dic:
res += 2
else:
currow = dic[row]
currow = [0] + currow + [11]
print(currow)
for i in range(1, len(currow)):
duration = currow[i] - currow[i-1] - 1
if duration < 4:
continue
elif duration == 4:
if currow[i]==5 or currow[i] == 7 or currow[i] == 9 or currow[i] == 11:
continue
else:
res += 1
elif duration > 4 and duration < 8:
res += 1
elif duration == 8:
if currow[i] == 9 or currow[i] == 11:
res += 1
else:
res += 2
elif duration == 9:
res += 2
return res
然后看看其他方法。从结果入手,可以知道,有效的4连发座位,一定是2345或者4567或者6789。则只要有预定座位是这几个数,则相应段的4连发不可用。当3种4连发都可用,结果+2,当只有其中1种可用,结果+1。当只有前两段或者后两段可用,结果+1。使用dic将没有预定的行排除,只遍历有预定的行。可以节省时间。
class Solution:
def maxNumberOfFamilies(self, n: int, reservedSeats: List[List[int]]) -> int:
dic = collections.defaultdict(list)
for row, column in reservedSeats:
dic[row].append(column)
res = (n - len(dic))*2
for row in dic:
left = 1 # the four seats from 2 to 5
middle = 1# the four seats from 4 to 7
right = 1## the four seats from 6 to 9
for i in dic[row]:
if i in [2,3,4,5]:
left = 0
if i in [4,5,6,7]:
middle = 0
if i in [6,7,8,9]:
right = 0
if left == 1 and middle == 1 and right == 1:
res += 2
elif left == 1 or middle == 1 or right == 1:
res += 1
return res