You are given an array of flight bookings bookings, where bookings[i] = [firsti, lasti, seatsi] represents a booking for flights firsti through lasti (inclusive) with seatsi seats reserved for each flight in the range.
Return an array answer of length n, where answer[i] is the total number of seats reserved for flight i.
We notice that each booking is for seats seats on all flights within a certain interval [first, last]. Therefore, we can use the idea of a difference array. For each booking, we add seats to the number at the first position and subtract seats from the number at the last + 1 position. Finally, we calculate the prefix sum of the difference array to get the total number of seats booked for each flight.
The time complexity is $O(n)$, where $n$ is the number of flights. Ignoring the space consumption of the answer, the space complexity is $O(1)$.
implSolution{#[allow(dead_code)]pubfncorp_flight_bookings(bookings:Vec<Vec<i32>>,n:i32)->Vec<i32>{letmutans=vec![0;nasusize];// Build the difference vector firstforbin&bookings{let(l,r)=((b[0]asusize)-1,(b[1]asusize)-1);ans[l]+=b[2];ifr<(nasusize)-1{ans[r+1]-=b[2];}}// Build the prefix sum vector based on the difference vectorforiin1..nasusize{ans[i]+=ans[i-1];}ans}}
We can also use a binary indexed tree, combined with the idea of difference, to implement the above operations. We can consider each booking as booking seats seats on all flights within a certain interval [first, last]. Therefore, for each booking, we add seats to the first position of the binary indexed tree and subtract seats from the last + 1 position of the binary indexed tree. Finally, we calculate the prefix sum for each position in the binary indexed tree to get the total number of seats booked for each flight.
The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of flights.
Here is a basic introduction to the binary indexed tree:
A binary indexed tree, also known as a "Binary Indexed Tree" or Fenwick tree. It can efficiently implement the following two operations:
Single Point Updateupdate(x, delta): Add a value delta to the number at position x in the sequence;
Prefix Sum Queryquery(x): Query the interval sum of the sequence [1,...x], that is, the prefix sum of position x.
The time complexity of these two operations is $O(\log n)$.