【贪心】B_016 航班预订统计(暴力 | 统计乘客数量)

一、题目描述

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;
}

复杂度分析

  • 时间复杂度:O(n2)O(n^2)
  • 空间复杂度:O(n)O(n)

尝试一:统计

边界错误:这题和 拼车 不同的是,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;
}

复杂度分析

  • 时间复杂度:O(n)O(n)
  • 空间复杂度:O(n)O(n)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章