差分数组的主要适用场景是频繁对原始数组的某个区间的元素进行增减。
# 差分数组工具类
class Difference:
# 差分数组
def __init__(self, nums: List[int]):
self.diff = [0] * len(nums)
# 根据初始数组构造差分数组
self.diff[0] = nums[0]
for i in range(1, len(nums)):
self.diff[i] = nums[i] - nums[i - 1]
# 给闭区间 [i, j] 增加 val(可以是负数)
def increment(self, i: int, j: int, val: int) -> None:
self.diff[i] += val
if j + 1 < len(self.diff):
self.diff[j + 1] -= val
# 返回结果数组
def result(self) -> List[int]:
res = [0] * len(self.diff)
# 根据差分数组构造结果数组
res[0] = self.diff[0]
for i in range(1, len(self.diff)):
res[i] = res[i - 1] + self.diff[i]
return res
1109. 航班预订统计
class Difference:
def __init__(self, nums: List[int]):
n = len(nums)
self.diff = [0] * n
self.diff[0] = nums[0]
for i in range(1, n):
self.diff[i] = nums[i] - nums[i - 1]
def increase(self, i, j, value):
self.diff[i] += value
if (j + 1) < len(self.diff):
self.diff[j + 1] -= value
def result(self) -> List[int]:
n = len(self.diff)
ans = [0] * n
ans[0] = self.diff[0]
for i in range(1, n):
ans[i] = ans[i - 1] + self.diff[i]
return ans
class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
nums = [0] * n
diff = Difference(nums)
for booking in bookings:
i = booking[0] - 1
j = booking[1] - 1
diff.increase(i, j, booking[-1])
return diff.result()
参考链接
https://labuladong.gitee.io/algo/di-yi-zhan-da78c/shou-ba-sh-48c1d/xiao-er-me-c304e/