一、題目描述
There are n flights, and they are labeled from 1 to n.
We have a list of flight bookings. The i-th booking bookings[i] = [i, j, k] means that we booked k seats from flights labeled i to j inclusive.
Return an array answer of length n, representing the number of seats booked on each flight in order of their label.
Input: bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5
Output: [10,55,45,25,25]
Constraints:
1 <= bookings.length <= 20000
1 <= bookings[i][0] <= bookings[i][1] <= n <= 20000
1 <= bookings[i][2] <= 10000
二、題解
方法一:暴力
與拼車 不同的是,這裏只是預定航班,並不會像拼車那樣下車,所以 i 號航班的預定只會增加而不會減少。直接枚舉即可。
public int[] corpFlightBookings(int[][] bookings, int n) {
int[] res = new int[n];
for (int[] book : bookings)
for (int k = book[0]; k <= book[1]; k++) {
res[k-1] += book[2];
}
return res;
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,
嘗試一:統計
邊界錯誤:這題和 拼車 不同的是,j
表示下航班的時機應該是 j+1
趟航班啓動時。
public int[] corpFlightBookings(int[][] bookings, int n) {
int N = bookings.length;
int[] map = new int[n+1];
List<Integer> list = new ArrayList<>();
for (int[] book : bookings) {
map[book[0]] += book[2];
map[book[1]] -= book[2];
}
int[] res = new int[n];
for (int i = 1; i <= n; i++) {
res[i-1] = map[i];
}
return res;
}
更正邏輯:把在 j
航班下飛機的人改爲 j + 1
趟,由於第 0 趟航班只有不會設計到其他航班,0 航班只有自己的預定人數。
public int[] corpFlightBookings(int[][] bookings, int n) {
int[] map = new int[n+2];
for (int[] book : bookings) {
map[book[0]] += book[2];
map[book[1]+1] -= book[2];
}
int[] res = new int[n];
for (int i = 0; i < n; i++) {
if (i == 0) res[i] = map[i+1];
else res[i] = res[i-1] + map[i+1];
}
return res;
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,