先给出一个TLE的方案,思路很简单:
1 class Solution: 2 def maxNumberOfFamilies(self, n: int, reservedSeats: 'List[List[int]]') -> int: 3 dic_row = dict() 4 for seats in reservedSeats: 5 row,position = seats[0],seats[1] 6 if row not in dic_row: 7 dic_row[row] = [position] 8 else: 9 dic_row[row].append(position) 10 count = 0 11 for i in range(1,n+1): 12 if i in dic_row: 13 row = dic_row[i] 14 if 2 not in row and 3 not in row and 4 not in row and 5 not in row and 6 not in row and 7 not in row and 8 not in row and 9 not in row: 15 count += 2 16 elif (2 not in row and 3 not in row and 4 not in row and 5 not in row) or (4 not in row and 5 not in row and 6 not in row and 7 not in row) or (6 not in row and 7 not in row and 8 not in row and 9 not in row): 17 count += 1 18 else: 19 count += 0 20 else: 21 count += 2 22 return count
再给一个AC的方案,简化了判断条件:
1 class Solution: 2 def maxNumberOfFamilies(self, n: int, reservedSeats: List[List[int]]) -> int: 3 seats = collections.defaultdict(int) 4 res = 0 5 6 for row, col in reservedSeats: 7 seats[row] = seats[row] | (1 << (col-1)) 8 9 for reserved in seats.values(): 10 curr = 0 11 curr += (reserved & int('0111100000', 2)) == 0 12 curr += (reserved & int('0000011110', 2)) == 0 13 curr += (reserved & int('0001111000', 2)) == 0 and curr == 0 14 15 res += curr 16 17 return res + 2 * (n - len(seats))
这种解决方案很巧妙,佩服。