5118-航班预订统计

前言

Weekly Contest 144航班预订统计数组

这里有 n 个航班,它们分别从 1n 进行编号。code

咱们这儿有一份航班预订表,表中第 i 条预订记录 bookings[i] = [i, j, k] 意味着咱们在从 ij 的每一个航班上预订了 k 个座位。索引

请你返回一个长度为 n 的数组 answer,按航班编号顺序返回每一个航班上预订的座位数。leetcode

示例:get

输入:bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5
输出:[10,55,45,25,25]

提示:test

  • 1 <= bookings.length <= 20000
  • 1 <= bookings[i][0] <= bookings[i][1] <= n <= 20000
  • 1 <= bookings[i][2] <= 10000

解题思路

本题题目的思路其实比较简答:统计

  1. 读取出每条预约记录bookings[i] = [i, j, k]的起点i,终点j和座位数k
  2. 处于起点ij之间的result[n]须要增长对应的座位数k,即若i<=n+1<=k(由于n为数组下标索引,因此须要n+1),则result[n]+=k

下面会经过题目的示例分析:数据

输入:bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5
输出:[10,55,45,25,25]

运算过程co

  1. 1行数据[1,2,10]表示起点是1,终点是2,座位数是10。因此result[0]+=10result[1]+=10。此时block

    result[0]=10
    result[1]=10
    result[2]=0
    result[3]=0
    result[4]=0
  2. 2行数据[2,3,20]表示起点是2,终点是3,座位数是20。因此result[1]+=20result[2]+=20。此时

    result[0]=10
    result[1]=30
    result[2]=20
    result[3]=0
    result[4]=0
  3. 3行数据[2,5,25]表示起点是2,终点是5,座位数是15。因此result[1]+=25result[2]+=25result[3]+=25result[4]+=25。此时

    result[0]=10
    result[1]=55
    result[2]=45
    result[3]=25
    result[4]=25

实现代码

/**
     * 5118. 航班预订统计
     * @param bookings
     * @param n
     * @return
     */
    public int[] corpFlightBookings(int[][] bookings, int n) {
        int[] result = new int[n]; 
        for (int i = 0; i < bookings.length; i++) { // 处理每一条预订记录
            int start = bookings[i][0];
            int end = bookings[i][1];
            int seat = bookings[i][2];
            for (int j = start - 1; j < end; j++) { // 给对应航班编号增长座位数
                result[j] += seat;
            }
        }
        return result;
    }
相关文章
相关标签/搜索