1109.航班预订统计
链接:1109.航班预订统计
难度:Medium
标签:数组、前缀和
简介:请你返回一个长度为 n 的数组 answer,其中 answer[i] 是航班 i 上预订的座位总数。
题解 1 - typescript
- 编辑时间:2021-11-14
- 执行用时:168ms
- 内存消耗:58.4MB
- 编程语言:typescript
- 解法介绍:差分。
function corpFlightBookings(bookings: number[][], n: number): number[] {
  const ans: number[] = new Array(n).fill(0);
  for (const [first, last, cnt] of bookings) {
    ans[first - 1] += cnt;
    if (last < n) ans[last] -= cnt;
  }
  for (let i = 1; i < n; i++) ans[i] += ans[i - 1];
  return ans;
}
题解 2 - typescript
- 编辑时间:2021-11-14
- 执行用时:1544ms
- 内存消耗:58.5MB
- 编程语言:typescript
- 解法介绍:遍历。
function corpFlightBookings(bookings: number[][], n: number): number[] {
  const ans: number[] = new Array(n).fill(0);
  for (const [first, last, cnt] of bookings) {
    for (let i = first; i <= last; i++) ans[i - 1] += cnt;
  }
  return ans;
}
题解 3 - typescript
- 编辑时间:2021-08-31
- 执行用时:164ms
- 内存消耗:58.4MB
- 编程语言:typescript
- 解法介绍:差分。
function corpFlightBookings(bookings: number[][], n: number): number[] {
  const nums = new Array(n).fill(0);
  for (const [first, last, seats] of bookings) {
    nums[first - 1] += seats;
    if (last < n) nums[last] -= seats;
  }
  for (let i = 1; i < n; i++) nums[i] += nums[i - 1];
  return nums;
}