class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
cols = n
rows = len(bookings)
matrix = [[0]*cols for _ in range(rows)]
for row in range(len(bookings)):
start, end, reserved = bookings[row]
for i in range(start1-1, end):
matrix[row][i] = reserved
ans = []
for col in range(cols):
tmp = 0
for row in range(rows):
tmp += matrix[row][col]
ans.append(tmp)
return ans
class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
ans = [0] * (n + 1)
for booking in bookings:
first, last, seats = booking
ans[first - 1] += seats
ans[last] -= seats
for i in range(1, n):
ans[i] += ans[i-1]
ans.pop()
return ans
看完後應該會有幾個疑問?
為什麼要 n+1 而不是 n 的空間?
為什麼只有兩個點紀錄,還一個用加的,一個用減的?
bookings: [[1,10, 100]] , n = 15
# (initially)
# index: [ 0,1,2,3,4,5,6,7,8,9, 10,11,12,13,14,15]
# result: [ 0,0,0,0,0,0,0,0,0,0, 0, 0, 0, 0, 0, 0] ------> result is of size n+1, indexed from 0 to 15
# (after loop iteration)
# result: [100,0,0,0,0,0,0,0,0,0,-100, 0, 0, 0, 0, 0]