当前位置:网站首页>【英雄哥七月集训】第 25天: 树状数组
【英雄哥七月集训】第 25天: 树状数组
2022-07-26 17:31:00 【如果我是温帅帅】
一、327. 区间和的个数
给你一个整数数组 nums 以及两个整数 lower 和 upper 。求数组中,值位于范围 [lower, upper] (包含 lower 和 upper)之内的 区间和的个数 。
区间和 S(i, j) 表示在 nums 中,位置从 i 到 j 的元素之和,包含 i 和 j (i ≤ j)。
示例 1:
输入:nums = [-2,5,-1], lower = -2, upper = 2
输出:3
解释:存在三个区间:[0,0]、[2,2] 和 [0,2] ,对应的区间和分别是:-2 、-1 、2 。
leetcode327 java
思路
1 前缀和
2 处理边界
3 离散化
4 遍历前缀和
class Solution {
public class BIT{
int n;
int[] tree;
public BIT(int x){
this.n = x;
this.tree = new int[x+1];
}
public int lowBit(int x){
return x&(-x);
}
public void update(int x){
while(x<=n){
tree[x]++;
x+=lowBit(x);
}
}
public int query(int x){
int ret = 0;
while(x!=0){
ret +=tree[x];
x-=lowBit(x);
}
return ret;
}
}
public int countRangeSum(int[] nums, int lower, int upper) {
long sum = 0;
int res = 0;
long[] presum = new long[nums.length+1];
//前缀和
for(int i = 0 ; i<nums.length ; i++){
sum += nums[i];
presum[i+1] = sum;
}
//处理边界
Set<Long> allnumbers = new TreeSet<>();
for(long pre:presum){
allnumbers.add(pre);
allnumbers.add(pre-lower);
allnumbers.add(pre-upper);
}
//离散化
Map<Long,Integer> map = new HashMap<>();
int idx = 0;
for(long x:allnumbers){
map.put(x,idx);
idx++;
}
//遍历前缀和
BIT bit = new BIT(map.size());
for(int i =0;i<presum.length;i++){
int left = map.get(presum[i]-upper), right = map.get(presum[i]-lower);
res +=bit.query(right+1)-bit.query(left);
bit.update( map.get(presum[i])+1);
}
return res;
}
}
总结
边栏推荐
猜你喜欢

AI sky covering DL multilayer perceptron

推荐效果不如意,不如试试飞桨图学习

2022年的PMP考试大纲是什么?

【集训Day2】Sculpture

来吧开发者!不只为了 20 万奖金,试试用最好的“积木”来一场头脑风暴吧!

JS closure simulates private variable interview questions and immediately executes function Iife

面试OPPO,16道题甩过来,我人傻了

菜鸟 CPaaS 平台微服务治理实践

LeetCode50天刷题计划(Day 5—— 最长回文子串 10.50-13:00)

4、 Service communication principle, code implementation
随机推荐
JS closure simulates private variable interview questions and immediately executes function Iife
Relative path and absolute path
【集训Day2】cinema ticket
Spark统一内存划分
Sign up now | oar hacker marathon phase III midsummer debut, waiting for you to challenge
[unity3d] rocker
Quartz trigger rule
【集训Day1】Spy dispatch
VS Code 格式化后 自动让函数名后有空格
Cross Site Request Forgery (CSRF)
CentOS installs docker and MySQL and redis environments
China polyisobutylene Market Research and investment value report (2022 Edition)
3、 Topic communication: create your own information format
【集训Day2】Sculpture
【翻译】为什么你需要一个API网关来管理对你的API的访问?
Spark数据格式UnsafeRow
Come on developer! Not only for the 200000 bonus, try the best "building blocks" for a brainstorming!
兆骑科创海外高层次人才引进平台,创业赛事活动路演
Redisdesktopmanager removes the upgrade prompt
Mondriaans‘s Dream(状态压缩DP)