:::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 ]
function corpFlightBookings(bookings: number[][], n: number): number[] {
let delta = new Array(n).fill(0);
for (let book of bookings) {
let [start, end, num] = book;
--start;
delta[start] += num;
if (end != n) {
delta[end] -= num;
}
}
for (let i = 1; i < n; i++) {
delta[i] += delta[i - 1];
}
return delta;
};
1094. 拼车
trips[i] = [num_passengers, start_location, end_location] 包含了第 i 组乘客的行程信息:
必须接送的乘客数量;
乘客的上车地点;
以及乘客的下车地点。
判断你的车是否可以顺利完成接送所有乘客的任务
var carPooling = function(trips, capacity) {
let delta = new Array();
for (let trip of trips) {
let [num, start, end] = trip;
delta[start] = (delta[start] || 0) + num;
delta[end] = (delta[end] || 0) - num;
}
let total = 0;
for (let i = 0; i < delta.length; i++) {
let cur = delta[i];
if (cur == undefined) continue;
total += cur;
if (total > capacity) return false;
}
return true;
};
1854. 人口最多的年份
var maximumPopulation = function(logs) {
const offset = 1950;
const len = 2050 - 1950 + 1;
let delta = new Array(len).fill(0);
for (let log of logs) {
delta[log[0] - offset] += 1;
delta[log[1] - offset] -= 1;
}
let max = 0;
let total = 0;
let index = 0;
for (let i = 0; i < len; i++) {
total += delta[i];
if (total > max) {
max = total;
index = i;
}
}
return index + offset;
};