当前位置:网站首页>前缀和相关:区域和检索 - 数组不可变、二维区域和检索 - 矩阵不可变...
前缀和相关:区域和检索 - 数组不可变、二维区域和检索 - 矩阵不可变...
2022-08-09 15:04:00 【凤求凰的博客】
给定一数组A。
前缀和:新建一数组B,数组中每一项B[i]保存A中[0…i]的和;
后缀和:新建一数组B,数组中每一项B[i]保存A中[i…n-1]的和;
前缀积:新建一数组B,数组中每一项B[i]保存A中[0…i]的积;
后缀积:新建一数组B,数组中每一项B[i]保存A中[i…n-1]的积;
一、区域和检索 - 数组不可变
class NumArray:
def __init__(self, nums: List[int]):
self.sums, pre = [0], 0
for v in nums:
self.sums.append(v + pre)
pre = self.sums[-1]
def sumRange(self, i: int, j: int) -> int:
return self.sums[j + 1] - self.sums[i]
二、二维区域和检索 - 矩阵不可变
核心思想:
class NumMatrix:
def __init__(self, matrix: List[List[int]]):
self.sum_matrix = [[0]*(len(matrix[i])+1) for i in range(len(matrix))]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
self.sum_matrix[i][j + 1] = self.sum_matrix[i][j] + matrix[i][j]
def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
sums = 0
for i in range(row1, row2 + 1):
sums += self.sum_matrix[i][col2 + 1] - self.sum_matrix[i][col1]
return sums
边栏推荐
猜你喜欢
随机推荐
FileInputStream与BufferedInputStream的区别
Zip包的读取与写入
properties文件的读取和写入
九章云极DataCanvas APS机器学习平台获得中国信通院“领先级”评级
【QT】QLayout: Attempting to add QLayout “to ***“, which already has a layout的终极解决方法
FPGA--基础语句、计数器、测试仿真语句(个人学习记录2022.7.20)
NAT种类及配置
VMware 虚拟机添加 2 张网卡 设置 NAT 与 桥接网络
DOS命令
VRRP详解与配置实例
Dolphin Scheduler 2.x版本部署篇
类定义中class和className中间的修饰词的作用有关问题
The practical skills Vim _1. Vim way of solving problems
The practical skills Vim _5. Move quickly between files and documents
vmware workstation 未能启动vmware
Fiddler抓包夜神模拟器
ping www.baidu.com虚拟机中ping百度
如何不使用第三个变量来交换两个数的值
RTP/RTCP协议的FFmpeg demux源码解析
MySql的备份与恢复