当前位置:网站首页>剑指offer专项突击版 --- 第 4 天
剑指offer专项突击版 --- 第 4 天
2022-07-31 05:09:00 【米兰的小红黑】
class Solution {
public int subarraySum(int[] nums, int k) {
Map<Integer,Integer> map = new HashMap<>();
map.put(0, 1);
int sum = 0;
int count = 0;
for (int i=0;i<nums.length;++i) {
sum += nums[i];
count += map.getOrDefault(sum-k, 0);
map.put(sum, map.getOrDefault(sum, 0) + 1);
}
return count;
}
}
class Solution {
public int findMaxLength(int[] nums) {
Map<Integer,Integer> map = new HashMap<>();
map.put(0,-1);
int sum = 0;
int ret = 0;
for(int i = 0; i < nums.length; i++){
sum += nums[i] == 0 ? -1 : 1;
if(map.containsKey(sum)){
ret = Math.max(ret, i - map.get(sum));
}else{
map.put(sum,i);
}
}
return ret;
}
}
class Solution {
public int pivotIndex(int[] nums) {
for(int i =0; i < nums.length; i++){
int num = 0;
for(int j = 0; j < nums.length; j++){
if(j < i){
num += nums[j];
}else if(j == i){
continue;
}else{
num -= nums[j];
}
}
if(num == 0){
return i;
}
}
return -1;
}
}
class NumMatrix {
int[][] sums;
public NumMatrix(int[][] matrix) {
int m = matrix.length;
if (m > 0) {
int n = matrix[0].length;
sums = new int[m + 1][n + 1];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
sums[i + 1][j + 1] = sums[i][j + 1] + sums[i + 1][j] - sums[i][j] + matrix[i][j];
}
}
}
}
public int sumRegion(int row1, int col1, int row2, int col2) {
return sums[row2 + 1][col2 + 1] - sums[row1][col2 + 1] - sums[row2 + 1][col1] + sums[row1][col1];
}
}
/**
* Your NumMatrix object will be instantiated and called as such:
* NumMatrix obj = new NumMatrix(matrix);
* int param_1 = obj.sumRegion(row1,col1,row2,col2);
*/
边栏推荐
猜你喜欢
随机推荐
快速掌握并发编程 --- 基础篇
mysql存储过程
Minio上传文件ssl证书不受信任
为什么要用Flink,怎么入门使用Flink?
Temporal客户端模型
[Detailed explanation of ORACLE Explain]
mysql stored procedure
Input length must be multiple of 8 when decrypting with padded cipher
DVWA安装教程(懂你的不懂·详细)
Go language study notes - dealing with timeout problems - Context usage | Go language from scratch
12个MySQL慢查询的原因分析
Moment Pool Cloud quickly installs packages such as torch-sparse and torch-geometric
MySQL forgot password
面试官,不要再问我三次握手和四次挥手
1. Get data - requests.get()
面试官:生成订单30分钟未支付,则自动取消,该怎么实现?
Mysql应用安装后找不到my.ini文件
如何将项目部署到服务器上(全套教程)
MySQL事务隔离级别详解
.NET-6.WinForm2.NanUI learning and summary