当前位置:网站首页>前缀和数组系列
前缀和数组系列
2022-07-06 06:42:00 【王六六的IT日常】
涉及三道题:
303. 区域和检索 - 数组不可变
304. 二维区域和检索 - 矩阵不可变
560. 和为 K 的子数组
如果要得到「区间和」,能想到最简单的方法就是遍历所求区间,循环相加即可。如果这种需求有很多,此时,时间复杂度为 O(n^2)
基于上面描述的场景,我们完全可以使用「前缀和」优化,前缀和数组中每个元素的值为区间[0…i]的元素和。
注意:
前缀和适用于不变数组;对于变化的数组,可以使用「线段树」,关于线段树的详细介绍可见 线段树详解
区域和检索 - 数组不可变
区域和检索 - 数组不可变
题目详情可见 :区域和检索 - 数组不可变
建议:preSum[]整体向后偏移一位,简便处理
如果求区间[2,4]的和,只需计算preSum[4 + 1] - preSum[2]即可
代码:
class NumArray {
// 记录前缀和的数组
private int[] preSum;
public NumArray(int[] nums) {
// preSum 从 1 开始,避免越界问题
preSum = new int[nums.length + 1];
for (int i = 1; i < preSum.length; i++) {
preSum[i] = preSum[i - 1] + nums[i - 1];
}
}
public int sumRange(int left, int right) {
return preSum[right + 1] - preSum[left];
}
}
二维区域和检索 - 矩阵不可变
题目详情可见 :二维区域和检索 - 矩阵不可变
如果求红色区间的和,只需求preSum[4,4] - preSum[1,4] - preSum[4,1] + preSum[1,1]即可
● preSum[4,4]:黄 + 蓝 + 绿 + 红
● preSum[1,4]:黄 + 蓝
● preSum[4,1]:黄 + 绿
● preSum[1,1]:黄
代码:
class NumMatrix {
private int[][] preSum;
public NumMatrix(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
preSum = new int[m + 1][n + 1];
for (int i = 1; i < m + 1; i++) {
for (int j = 1; j < n + 1; j++) {
preSum[i][j] = preSum[i - 1][j] + preSum[i][j - 1] - preSum[i - 1][j - 1] + matrix[i - 1][j - 1];
}
}
}
public int sumRegion(int row1, int col1, int row2, int col2) {
return preSum[row2 + 1][col2 + 1] - preSum[row1][col2 + 1] - preSum[row2 + 1][col1] + preSum[row1][col1];
}
}
和为 K 的子数组
题目详情可见 和为 K 的子数组
借鉴「两数和」的思路,利用HashMap。
代码:
public int subarraySum(int[] nums, int k) {
Map<Integer, Integer> preSum = new HashMap<>();
preSum.put(0, 1);
int sum = 0;
int res = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
int target = sum - k;
if (preSum.containsKey(target)) res += preSum.get(target);
preSum.put(sum, preSum.getOrDefault(sum, 0) + 1);
}
return res;
}
边栏推荐
- At the age of 26, I changed my career from finance to software testing. After four years of precipitation, I have been a 25K Test Development Engineer
- Distributed system basic (V) protocol (I)
- ML之shap:基于adult人口普查收入二分类预测数据集(预测年收入是否超过50k)利用Shap值对XGBoost模型实现可解释性案例之详细攻略
- Leetcode daily question (1870. minimum speed to arrive on time)
- The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
- Leetcode daily question (1997. first day where you have been in all the rooms)
- LeetCode - 152 乘积最大子数组
- 成功解决AttributeError: Can only use .cat accessor with a ‘category‘ dtype
- Do you really know the use of idea?
- In English translation of papers, how to do a good translation?
猜你喜欢

生物医学本地化翻译服务

mysql的基础命令

The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
![[ 英语 ] 语法重塑 之 动词分类 —— 英语兔学习笔记(2)](/img/3c/c25e7cbef9be1860842e8981f72352.png)
[ 英语 ] 语法重塑 之 动词分类 —— 英语兔学习笔记(2)

Biomedical localization translation services

How much is the price for the seal of the certificate

Windows Server 2016 standard installing Oracle

基于PyTorch和Fast RCNN快速实现目标识别

AttributeError: Can‘t get attribute ‘SPPF‘ on <module ‘models.common‘ from ‘/home/yolov5/models/comm

【刷题】怎么样才能正确的迎接面试?
随机推荐
翻译公司证件盖章的价格是多少
Simple use of MySQL database: add, delete, modify and query
Facebook AI & Oxford proposed a video transformer with "track attention" to perform SOTA in video action recognition tasks
【软件测试进阶第1步】自动化测试基础知识
How to convert flv file to MP4 file? A simple solution
Difference between backtracking and recursion
Address bar parameter transmission of list page based on jeecg-boot
Map of mL: Based on the adult census income two classification prediction data set (whether the predicted annual income exceeds 50K), use the map value to realize the interpretable case of xgboost mod
云服务器 AccessKey 密钥泄露利用
AttributeError: Can‘t get attribute ‘SPPF‘ on <module ‘models.common‘ from ‘/home/yolov5/models/comm
Monotonic stack
It is necessary to understand these characteristics in translating subtitles of film and television dramas
查询字段个数
Successfully solved typeerror: data type 'category' not understood
金融德语翻译,北京专业的翻译公司
Day 248/300 thoughts on how graduates find jobs
Automated test environment configuration
UNIPRO Gantt chart "first experience": multi scene exploration behind attention to details
我的创作纪念日
Summary of leetcode's dynamic programming 4