当前位置:网站首页>前缀和数组系列
前缀和数组系列
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;
}
边栏推荐
- How to reconstruct the class explosion caused by m*n strategies?
- What are the characteristics of trademark translation and how to translate it?
- [brush questions] how can we correctly meet the interview?
- ROS2安装及基础知识介绍
- Reflex WMS medium level series 3: display shipped replaceable groups
- 成功解决TypeError: data type ‘category‘ not understood
- After working for 10 years, I changed to a programmer. Now I'm 35 + years old and I'm not anxious
- 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
- 翻译生物医学说明书,英译中怎样效果佳
- Wish Dragon Boat Festival is happy
猜你喜欢

26岁从财务转行软件测试,4年沉淀我已经是25k的测开工程师...

Market segmentation of supermarket customers based on purchase behavior data (RFM model)

如何做好金融文献翻译?

Changes in the number of words in English papers translated into Chinese

How to translate professional papers and write English abstracts better

Pallet management in SAP SD delivery process

云服务器 AccessKey 密钥泄露利用

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

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

【刷题】怎么样才能正确的迎接面试?
随机推荐
Today's summer solstice
Erreur de type résolue avec succès: type de données « catégorie» non sous - jacente
P5706 [deep foundation 2. Example 8] redistributing fat house water -- February 13, 2022
ML之shap:基于adult人口普查收入二分类预测数据集(预测年收入是否超过50k)利用Shap值对XGBoost模型实现可解释性案例之详细攻略
Call, apply, bind rewrite, easy to understand with comments
Brief introduction to the curriculum differences of colleges and universities at different levels of machine human major -ros1/ros2-
Tms320c665x + Xilinx artix7 DSP + FPGA high speed core board
Suspended else
E-book CHM online CS
自动化测试环境配置
Day 246/300 ssh连接提示“REMOTE HOST IDENTIFICATION HAS CHANGED! ”
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
How much is the price for the seal of the certificate
Fedora/rehl installation semanage
【刷题】怎么样才能正确的迎接面试?
[ 英语 ] 语法重塑 之 英语学习的核心框架 —— 英语兔学习笔记(1)
C语言_双创建、前插,尾插,遍历,删除
LeetCode每日一题(1997. First Day Where You Have Been in All the Rooms)
Py06 dictionary mapping dictionary nested key does not exist test key sorting
Biomedical localization translation services