Leetcode 1109 flight reservation statistics

Time:2021-10-21

subject

here you are   n   Flights, numbered from 1 to n.

There is a flight reservation form   Bookings, table No   i   Reservation records   bookings[i] = [firsti, lasti, seatsi]   Means from firstI   Seatsi is booked on each flight to lasti (including firstI and lasti)   Seats.

Please return an array with length n   Answer, where answer [i] is the total number of seats reserved on flight I.

Source: leetcode
Link: https://leetcode-cn.com/probl…
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Example 1:

Input: bookings = [[1,2,10], [2,3,20], [2,5,25]], n = 5
Output: [10,55,45,25,25]
Explanation:
Flight number 1 2 3 4 5
Booking record 1:10
Reservation record 2:20
Booking record 3:25
Total seats: 10 55 45 25
Therefore, answer = [10,55,45,25,25]

Example 2:

Input: bookings = [[1,2,10], [2,2,15]], n = 2
Output: [10,25]
Explanation:
Flight number 1 2
Booking record 1:10
Booking record 2:15
Total seats: 10 25
Therefore, answer = [10,25]
 

Tips:

1 <= n <= 2 * 104
1 <= bookings.length <= 2 * 104
bookings[i].length == 3
1 <= firsti <= lasti <= n
1 <= seatsi <= 104

Problem solution

1. Violence (double loop problem solving)

/**
 * @param {number[][]} bookings
 * @param {number} n
 * @return {number[]}
 */
var corpFlightBookings = function(bookings, n) {
    let res = new Array(n).fill(0);
    for(let i = 0; i < bookings.length; i++){
        for(let j = bookings[i][0]; j <= bookings[i][1]; j++){
            res[j-1] += bookings[i][2];
        }
    }
    return res;
};

2. Difference

By adding a value Val to the interval [l, R] as a whole, we can see the impact on the difference fraction group arr as two parts:
(1) Left end point of interval: arr [l] + = val. since difference is the reverse process of prefix sum, this operation will increase the value Val for all positions with subscript greater than or equal to l for future queries;
(2) Right end point of the interval: arr [R + 1] – = val. since we expect to only affect the interval [l, R], we need to devalue the position where the subscript is greater than R, and the value of the right end will not be affected by the previous operation.
The specific codes are as follows

/**
 * @param {number[][]} bookings
 * @param {number} n
 * @return {number[]}
 */
var corpFlightBookings = function(bookings, n) {
    let res = new Array(n).fill(0);
    for(let i = 0; i < bookings.length; i++){
        //Left end point of interval
        res[bookings[i][0] - 1] += bookings[i][2];
        //Right end point of section + 1
        if(bookings[i][1] < n){
            res[bookings[i][1]] -= bookings[i][2];
        }
    }
    for(let i = 1; i < n; i++){
        res[i] += res[i - 1];
    }
    return res;
};