【leetcode】1109. Corporate Flight Bookings

题目如下:

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 jinclusive.

Return an array answer of length n, representing the number of seats booked on each flight in order of their label.

 

Example 1:

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

解题思路:这种区间问题,我首先想到的是线段树,当然本题线段树似乎不是最优答案,因为我的解法耗时在2S左右。遍历bookings,把每个item的bookings[i][2]累加到相应的数的节点中,最后统一计算总数即可。

代码如下:

class Solution(object):
    def corpFlightBookings(self, bookings, n):
        """
        :type bookings: List[List[int]]
        :type n: int
        :rtype: List[int]
        """
        segment = [0] * (4 * n + 1)
        def recursive(start,end,low,high,inx,val):
            #print start,end,low,high,inx,val
            if low > high:
                return
            if start == low and end == high:
                segment[inx] += val
                return
            mid = (low + high)/2
            #if start == low and end == high:
            #    recursive(start, mid, low, mid, inx * 2, val)
            #    recursive(mid + 1, end, mid + 1, high, inx * 2 + 1, val)
            if end <= mid:
                recursive(start,end,low,mid,inx*2,val)
            elif start > mid:
                recursive(start, end, mid + 1, high, inx * 2+1, val)
            else:
                recursive(start, mid, low, mid, inx * 2, val)
                recursive(mid+1, end, mid+1, high, inx * 2 + 1, val)

        res = [0] * n
        def query(inx,low,high,segment_inx,node_inx):
            if segment_inx >= len(segment):
                return
            mid = (low + high)/2
            res[node_inx] += segment[segment_inx]
            if inx <= mid:
                query(inx,low,mid,segment_inx*2,node_inx)
            else:
                query(inx, mid+1, high, segment_inx * 2 + 1, node_inx)

        for (start,end,val) in bookings:
            recursive(start,end,1,n,1,val)

        for i in range(1,n+1):
            query(i,1,n,1,i-1)
        return res

 

posted @ 2019-07-11 14:53  seyjs  阅读(522)  评论(0编辑  收藏  举报