LC1109.航班预订统计

image.png

思路

  • 差分:和ACW797很像,参考那一题即可。
  • 注意处理边界的情况,差分数组需要开大一点,因为最后可能会超过范围

    代码

    1. class Solution {
    2. public:
    3. vector<int> corpFlightBookings(vector<vector<int>>& bookings, int n) {
    4. // 航班编号从1开始
    5. int n_books = bookings.size();
    6. vector<int> seats_list(n, 0);
    7. vector<int> diff(n + 1, 0);
    8. for (int i = 0; i < n_books; ++i) {
    9. int begin_pos = bookings[i][0] - 1;
    10. int end_pos = bookings[i][1] - 1;
    11. int add_nums = bookings[i][2];
    12. diff[begin_pos] += add_nums;
    13. diff[end_pos + 1] -= add_nums;
    14. }
    15. for (int i = 0; i < n; ++i) {
    16. if (i == 0) {
    17. seats_list[0] = diff[0];
    18. } else {
    19. seats_list[i] = seats_list[i - 1] + diff[i];
    20. }
    21. }
    22. return seats_list;
    23. }
    24. };