leetcode 327.Count of Range Sum
来源:互联网 发布:java 在线视频技术 编辑:程序博客网 时间:2024/06/04 17:48
前缀和,线段树+离散化
题意:
给一个数组,和一个上界和下界.
统计数组里有多少个区间的区间和在上界和下界之间.
思路:
有一种套路叫区间统计转化为前缀统计.
interval[i,j]∈[lower,upper],相当于prefix[j]-prefix[i-1]∈[lower,upper].
再变换下,就是prefix[i-1]∈[prefix[j]-upper,prefix[j]-lower]
先求前缀和,然后以前缀和的值为下标,值的数量为值,建立空的值域线段树.
之后从左到右扫描,对每个前缀和prefix[j],根据上面的式子,从线段树里询问有多少个prefix[i-1]满足条件.
更新答案后,把prefix[j]插入到线段树里.
扫描是O(n)步,每步的询问和插入是O(logn)的,因此总复杂度是O(nlogn).
有几点要注意:
1.要预先向线段树插入prefix[-1]=0这样的特殊前缀和
2.由于是值域线段树,因此值域很大的情况下需要先离散化
3.数据是int范围,但前缀和是long long范围
总结:
求前缀和,一边统计答案,一边维护前缀和的值域线段树.
0 0
- <LeetCode OJ> 327. Count of Range Sum
- leetcode 327. Count of Range Sum
- Leetcode 327. Count of Range Sum[hard]
- LeetCode 327. Count of Range Sum
- leetcode 327.Count of Range Sum
- LeetCode 327. Count of Range Sum
- LeetCode 327. Count of Range Sum
- leetcode 327. Count of Range Sum
- [leetcode]327. Count of Range Sum
- leetcode 327. Count of Range Sum
- leetcode Count of Range Sum
- LeetCode Count of Range Sum
- [LeetCode]Count of Range Sum
- Leetcode Count of Range Sum
- leetcode Count of Range Sum
- []LeetCode]Count of Range Sum
- [LeetCode] Count of Range Sum
- Count of Range Sum(leetcode)
- js学习笔记(一)实现Bingo卡片
- 【C++ 学习】那些习以为常的背后之一从0开始的计数
- Android 自定义View绘图篇之基础
- JAVA IO
- oracle存储过程
- leetcode 327.Count of Range Sum
- 结构体字节对齐
- 【翻译】Pandas 十分钟入门
- TrackRender
- 关于JS内存泄漏
- 小话设计模式(十二)代理模式
- Android 四大大图片缓存(Imageloader,Picasso,Glide,Fresco)原理、特性对比
- 如何向别人问问题
- 泊松分布