当前位置:网站首页>前缀和数组系列
前缀和数组系列
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;
}
边栏推荐
- Office-DOC加载宏-上线CS
- AttributeError: Can‘t get attribute ‘SPPF‘ on <module ‘models.common‘ from ‘/home/yolov5/models/comm
- In English translation of papers, how to do a good translation?
- UNIPRO Gantt chart "first experience": multi scene exploration behind attention to details
- [ 英语 ] 语法重塑 之 动词分类 —— 英语兔学习笔记(2)
- 女生学软件测试难不难 入门门槛低,学起来还是比较简单的
- The registration password of day 239/300 is 8~14 alphanumeric and punctuation, and at least 2 checks are included
- Distributed system basic (V) protocol (I)
- After working for 10 years, I changed to a programmer. Now I'm 35 + years old and I'm not anxious
- Cobalt Strike特征修改
猜你喜欢
How much is it to translate Chinese into English for one minute?
接口自动化测试实践指导(上):接口自动化需要做哪些准备工作
Apache DolphinScheduler源码分析(超详细)
26岁从财务转行软件测试,4年沉淀我已经是25k的测开工程师...
The internationalization of domestic games is inseparable from professional translation companies
翻译生物医学说明书,英译中怎样效果佳
Monotonic stack
Attributeerror: can 't get attribute' sppf 'on < module' models. Common 'from' / home / yolov5 / Models / comm
(practice C language every day) reverse linked list II
How to translate biomedical instructions in English
随机推荐
MySQL high frequency interview 20 questions, necessary (important)
删除外部表源数据
Day 248/300 关于毕业生如何找工作的思考
My creation anniversary
SAP SD发货流程中托盘的管理
Fedora/REHL 安装 semanage
[brush questions] how can we correctly meet the interview?
如何做好金融文献翻译?
钓鱼&文件名反转&office远程模板
基于购买行为数据对超市顾客进行市场细分(RFM模型)
Monotonic stack
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
Biomedical English contract translation, characteristics of Vocabulary Translation
Use shortcut LNK online CS
pymongo获取一列数据
Is it difficult for girls to learn software testing? The threshold for entry is low, and learning is relatively simple
On the first day of clock in, click to open a surprise, and the switch statement is explained in detail
Reflex WMS medium level series 3: display shipped replaceable groups
机器学习植物叶片识别
Modify the list page on the basis of jeecg boot code generation (combined with customized components)