LeetCode刷题 插分数组技巧
具体方法参考labuladong的论那些小而美的算法技巧:差分数组/前缀和
方法一: 使用hashmap来辅助的暴力遍历叠加解法(超时)
class Solution(object):
# 用hash辅助的暴力法, 但是会超时
def corpFlightBookings(self, bookings, n):
"""
:type bookings: List[List[int]]
:type n: int
:rtype: List[int]
"""
if n == 0:
return []
hashmap = dict()
for book in bookings:
for i in range(book[0] - 1, book[1]):
hashmap[i] = hashmap.get(i, 0) + book[2]
res = []
for k in range(n):
res.append(hashmap.get(k, 0))
return res
方法二: 利用插分数组, 多次对区间进行加减
import copy
class Difference:
def __init__(self, n):
self.n = n
self.nums = [0] * n
self.diff = copy.copy(self.nums)
for i in range(1, n):
self.diff[i] = self.nums[i] - self.nums[i-1]
def increase(self, i, j, k):
self.diff[i] += k
if j + 1 < self.n:
self.diff[j + 1] -= k
def result(self):
res = copy.copy(self.diff)
for i in range(1, self.n):
res[i] += res[i - 1]
return res
class Solution(object):
# 用hash辅助的暴力法, 但是会超时
def corpFlightBookings(self, bookings, n):
df = Difference(n)
for book in bookings:
df.increase(book[0]-1, book[1]-1, book[2])
return df.result()