forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
7d5f8f3
commit 23aa611
Showing
1 changed file
with
11 additions
and
0 deletions.
There are no files selected for viewing
11 changes: 11 additions & 0 deletions
11
Segment_Tree/2031.Count-Subarrays-With-More-Ones-Than-Zeros/Readme.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
### 2031.Count-Subarrays-With-More-Ones-Than-Zeros | ||
|
||
对于区间的问题,我们很容想到尝试前缀和。我们令diff[i]表示前i个数字里元素1与元素0个数之差。那么对于以i为右边界的合法区间,我们希望它对应的左边界位置j有什么性质呢?显然,我们希望```diff[j] < diff[i]```即可。这样从[j+1:i]这个区间里的元素1一定比0多。有多少个这样的j,就有多少个以i为右边界的合法区间。 | ||
|
||
那么有多少个j满足这个条件呢?我们显然需要在i之前,记录下所有diff[j]的值并且统计频次,并且累加那些差值小于diff[i]的频次。 | ||
|
||
比如,我们令nums[k]表示diff为k出现的频次,即有多少个j,满足长度为j的前缀区间里元素1与元素0个数之差为k。对于每一个右边界为i的合法区间,我们需要累加```nums[0]+nums[1]+..+nums[diff[i]-1]```,这个数目就是左边界的数目。计算出这个答案之后,我们还需要更新```nums[diff[i]]+=1```,因为下一个回合的diff[i+1]会再次用到更新后的nums数组。 | ||
|
||
由此可见,我们需要一个数据结构,能够快速求出nums数组里的指定区间和(更确切地说是前缀和),同时也要支持对nums任意单点的高效修改。显然这样的数据结果,binary index tree是再合适不过了。 | ||
|
||
此题需要额外处理的一个问题的是:diff的数值范围可以是-10000到+10000,即我们需要记录从nums[-100000]到nums[+100000]。但是树状数组的index必须都是正数。所以我们需要一个```offset=1e5+1```,将差值[-1e5,1e5]映射到正数[1, 2e5+2]上。注意在这里的模板中,树状数组里有意义的元素下标从1开始。 |