问题描述

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

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

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

 

示例:

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

提示:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/corporate-flight-bookings

解答

class Solution {
    public int[] corpFlightBookings(int[][] bookings, int n) {
        int[] answer = new int[n];
        for(int[] t:bookings){
            answer[t[0]-1]+=t[2];
            if(t[1]<n)answer[t[1]]-=t[2];
        }
        for(int i=1;i<n;i++)answer[i] += answer[i-1];
        return answer;
    }
}

 本题用到了差分数组,可以参考如下链接:

https://mp.weixin.qq.com/s/9L6lz0XDZ9gi-d_iPrSs8Q