Leetcode 1109. Flight booking statistics

Leetcode 1109. Flight booking statistics

topic

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

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

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

Example:

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

Ideas

  • First look at the order of magnitude, you can’t be violent
  • Interval and problems like this can be solved by using difference prefix sum
  • Now briefly explain the form of the difference prefix sum:
下标     0 1 2 3 4 5 6
value   0 1 0 0 0 -1 0
前缀和   0 1 1 1 1 0 0  
  • See that, set the value at the starting point of the interval, and set the opposite of the starting point at the end of the interval+1, so that after finishing the prefix sum, the value of the entire interval is 1.
  • So, we can use the idea of ​​difference prefix sum to solve this problem

Code-Golang

func corpFlightBookings(bookings [][]int, n int) []int {
    res := [20000 + 2]int{}

    for _, booking := range bookings {
        res[booking[0]] += booking[2]
        res[booking[1] + 1] -= booking[2]
    }

    for i := 1;i < len(res);i++ {
        res[i] += res[i - 1]
    }

    return res[1:n+1]
}

Note:
If you want to learn a language quickly, just write more

Guess you like

Origin blog.csdn.net/weixin_43891775/article/details/113120062