LC1109.航班预订统计
思路
- 差分:和ACW797很像,参考那一题即可。
注意处理边界的情况,差分数组需要开大一点,因为最后可能会超过范围
代码
class Solution {
public:
vector<int> corpFlightBookings(vector<vector<int>>& bookings, int n) {
// 航班编号从1开始
int n_books = bookings.size();
vector<int> seats_list(n, 0);
vector<int> diff(n + 1, 0);
for (int i = 0; i < n_books; ++i) {
int begin_pos = bookings[i][0] - 1;
int end_pos = bookings[i][1] - 1;
int add_nums = bookings[i][2];
diff[begin_pos] += add_nums;
diff[end_pos + 1] -= add_nums;
}
for (int i = 0; i < n; ++i) {
if (i == 0) {
seats_list[0] = diff[0];
} else {
seats_list[i] = seats_list[i - 1] + diff[i];
}
}
return seats_list;
}
};