:::info 差分:通常用于统计区间内的数量变化 :::

1109. 航班预订统计

📢 最后一班,无需操作
case 1: bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5
第一遍, 记录0 - n 时刻上车人数, (正数表示上车,负数表示下车)
[ 10, 45, -10, -20, 0 ]
第二遍
[ 10, 55, 45, 25, 25 ]

  1. function corpFlightBookings(bookings: number[][], n: number): number[] {
  2. let delta = new Array(n).fill(0);
  3. for (let book of bookings) {
  4. let [start, end, num] = book;
  5. --start;
  6. delta[start] += num;
  7. if (end != n) {
  8. delta[end] -= num;
  9. }
  10. }
  11. for (let i = 1; i < n; i++) {
  12. delta[i] += delta[i - 1];
  13. }
  14. return delta;
  15. };

1094. 拼车

trips[i] = [num_passengers, start_location, end_location] 包含了第 i 组乘客的行程信息:
必须接送的乘客数量;
乘客的上车地点;
以及乘客的下车地点。

判断你的车是否可以顺利完成接送所有乘客的任务

  1. var carPooling = function(trips, capacity) {
  2. let delta = new Array();
  3. for (let trip of trips) {
  4. let [num, start, end] = trip;
  5. delta[start] = (delta[start] || 0) + num;
  6. delta[end] = (delta[end] || 0) - num;
  7. }
  8. let total = 0;
  9. for (let i = 0; i < delta.length; i++) {
  10. let cur = delta[i];
  11. if (cur == undefined) continue;
  12. total += cur;
  13. if (total > capacity) return false;
  14. }
  15. return true;
  16. };

1854. 人口最多的年份

  1. var maximumPopulation = function(logs) {
  2. const offset = 1950;
  3. const len = 2050 - 1950 + 1;
  4. let delta = new Array(len).fill(0);
  5. for (let log of logs) {
  6. delta[log[0] - offset] += 1;
  7. delta[log[1] - offset] -= 1;
  8. }
  9. let max = 0;
  10. let total = 0;
  11. let index = 0;
  12. for (let i = 0; i < len; i++) {
  13. total += delta[i];
  14. if (total > max) {
  15. max = total;
  16. index = i;
  17. }
  18. }
  19. return index + offset;
  20. };