航班预定统计(差分数组+前缀和)

题目链接:https://leetcode-cn.com/problems/corporate-flight-bookings
题目描述:
这里有 n 个航班,它们分别从 1 到 n 进行编号。
有一份航班预订表 bookings ,表中第 i 条预订记录 bookings[i] = [firsti, lasti, seatsi] 意味着在从 firsti 到 lasti (包含 firsti 和 lasti )的 每个航班 上预订了 seatsi 个座位。
请你返回一个长度为 n 的数组 answer,其中 answer[i] 是航班 i 上预订的座位总数。


提示:

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

题解:
方法1:暴力法(超时)


class Solution {
public:
    vector<int> corpFlightBookings(vector<vector<int>>& bookings, int n) {
        vector<int> ans(n, 0);
        for(int i = 0; i < bookings.size(); i++)
        {
            for(int j = bookings[i][0]; j <= bookings[i][1]; j++)
            {
                int temp = bookings[i][2];
                cout  << temp << endl;
                ans[j - 1] += temp;
            }
        }
        return ans;
    }
};

方法2:差分数组+前缀和

class Solution {
public:
    vector<int> corpFlightBookings(vector<vector<int>>& bookings, int n) {
        vector<int> ans(n, 0);
        for(auto book:bookings)
        {
            ans[book[0] - 1] += book[2];
            if(book[1] < n)
                ans[book[1]] -= book[2];
        }
        for(int i = 1; i < n; i++)
        {
            ans[i] += ans[i - 1];
        }
        return ans;
    }
};
原文地址:https://www.cnblogs.com/ZigHello/p/15210319.html