【貪心】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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章