Skip to content

Commit 8a567b4

Browse files
committed
✨feat: add 795
1 parent 93169b2 commit 8a567b4

File tree

3 files changed

+216
-0
lines changed

3 files changed

+216
-0
lines changed

Index/单调栈.md

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
| [503. 下一个更大元素 II](https://leetcode-cn.com/problems/next-greater-element-ii/) | [LeetCode 题解链接](https://leetcode-cn.com/problems/next-greater-element-ii/solution/cong-po-su-jie-fa-de-jiao-du-qu-li-jie-d-trht/) | 中等 | 🤩🤩🤩 |
99
| [654. 最大二叉树](https://leetcode.cn/problems/maximum-binary-tree/) | [LeetCode 题解链接](https://leetcode.cn/problems/maximum-binary-tree/solution/by-ac_oier-s0wc/) | 中等 | 🤩🤩🤩🤩🤩 |
1010
| [739. 每日温度](https://leetcode.cn/problems/daily-temperatures/) | [LeetCode 题解链接](https://leetcode.cn/problems/daily-temperatures/solution/by-ac_oier-aj5k/) | 中等 | 🤩🤩🤩🤩 |
11+
| [795. 区间子数组个数](https://leetcode.cn/problems/number-of-subarrays-with-bounded-maximum/) | [LeetCode 题解链接](https://leetcode.cn/problems/number-of-subarrays-with-bounded-maximum/solution/by-ac_oier-gmpt/) | 中等 | 🤩🤩🤩🤩🤩 |
1112
| [901. 股票价格跨度](https://leetcode.cn/problems/online-stock-span/) | [LeetCode 题解链接](https://leetcode.cn/problems/online-stock-span/solution/by-ac_oier-m8g7/) | 中等 | 🤩🤩🤩🤩 |
1213
| [907. 子数组的最小值之和](https://leetcode.cn/problems/sum-of-subarray-minimums/) | [LeetCode 题解链接](https://leetcode.cn/problems/sum-of-subarray-minimums/solution/by-ac_oier-h9cd/) | 中等 | 🤩🤩🤩🤩 |
1314
| [1475. 商品折扣后的最终价格](https://leetcode.cn/problems/final-prices-with-a-special-discount-in-a-shop/) | [LeetCode 题解链接](https://leetcode.cn/problems/final-prices-with-a-special-discount-in-a-shop/solution/by-ac_oier-hw5b/) | 简单 | 🤩🤩🤩🤩🤩 |

Index/模拟.md

+1
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@
106106
| [788. 旋转数字](https://leetcode.cn/problems/rotated-digits/) | [LeetCode 题解链接](https://leetcode.cn/problems/rotated-digits/solution/by-ac_oier-9qpw/) | 中等 | 🤩🤩🤩🤩 |
107107
| [791. 自定义字符串排序](https://leetcode.cn/problems/custom-sort-string/) | [LeetCode 题解链接](https://leetcode.cn/problems/custom-sort-string/solution/by-ac_oier-ali0/) | 中等 | 🤩🤩🤩🤩🤩 |
108108
| [794. 有效的井字游戏](https://leetcode-cn.com/problems/valid-tic-tac-toe-state/) | [LeetCode 题解链接](https://leetcode-cn.com/problems/valid-tic-tac-toe-state/solution/gong-shui-san-xie-fen-qing-kuang-tao-lun-pikn/) | 中等 | 🤩🤩🤩🤩 |
109+
| [795. 区间子数组个数](https://leetcode.cn/problems/number-of-subarrays-with-bounded-maximum/) | [LeetCode 题解链接](https://leetcode.cn/problems/number-of-subarrays-with-bounded-maximum/solution/by-ac_oier-gmpt/) | 中等 | 🤩🤩🤩🤩🤩 |
109110
| [796. 旋转字符串](https://leetcode-cn.com/problems/rotate-string/) | [LeetCode 题解链接](https://leetcode-cn.com/problems/rotate-string/solution/by-ac_oier-bnkx/) | 简单 | 🤩🤩🤩 |
110111
| [804. 唯一摩尔斯密码词](https://leetcode-cn.com/problems/unique-morse-code-words/) | [LeetCode 题解链接](https://leetcode-cn.com/problems/unique-morse-code-words/solution/by-ac_oier-a9hv/) | 简单 | 🤩🤩🤩 |
111112
| [806. 写字符串需要的行数](https://leetcode-cn.com/problems/number-of-lines-to-write-string/) | [LeetCode 题解链接](https://leetcode-cn.com/problems/number-of-lines-to-write-string/solution/by-ac_oier-5hg2/) | 简单 | 🤩🤩🤩🤩 |
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,214 @@
1+
### 题目描述
2+
3+
这是 LeetCode 上的 **[795. 区间子数组个数](https://leetcode.cn/problems/number-of-subarrays-with-bounded-maximum/solution/by-ac_oier-gmpt/)** ,难度为 **中等**
4+
5+
Tag : 「模拟」、「单调栈」
6+
7+
8+
9+
给你一个整数数组 `nums` 和两个整数:`left``right`
10+
11+
找出 `nums` 中连续、非空且其中最大元素在范围 $[left, right]$ 内的子数组,并返回满足条件的子数组的个数。
12+
13+
生成的测试用例保证结果符合 `32-bit` 整数范围。
14+
15+
示例 1:
16+
``` 
17+
输入:nums = [2,1,4,3], left = 2, right = 3
18+
19+
输出:3
20+
21+
解释:满足条件的三个子数组:[2], [2, 1], [3]
22+
```
23+
示例 2:
24+
``` 
25+
输入:nums = [2,9,2,5,6], left = 2, right = 8
26+
27+
输出:7
28+
```
29+
30+
提示:
31+
* $1 <= nums.length <= 10^5$
32+
* $0 <= nums[i] <= 10^9$
33+
* $0 <= left <= right <= 10^9$
34+
35+
---
36+
37+
### 单调栈
38+
39+
为了方便,我们令 $[left, right]$ 为 $[a, b]$。
40+
41+
一个容易想到的思路是使用「单调栈」。
42+
43+
**统计所有最大值范围在 $[a, b]$ 之间的子数组个数,可等价为统计每一个范围落在 $[a, b]$ 之间的 $nums[i]$ 作为最大值时子数组的个数。**
44+
45+
由此可以进一步将问题转换为:求解每个 $nums[i]$ 作为子数组最大值时,最远的合法左右端点的位置。也就是求解每一个 $nums[i]$ 左右最近一个比其“大”的位置,这可以使用「单调栈」来进行求解。
46+
47+
> 对于单调栈不了解的同学,可以看前置 🧀 : [【RMQ 专题】关于 RMQ 的若干解法](https://mp.weixin.qq.com/s?__biz=MzU4NDE3MTEyMA==&mid=2247493262&idx=1&sn=2d8e192a5767b49b9a13a6192ab3b833)
48+
49+
**统计所有 $nums[i]$ 对答案的贡献即是最终答案,但我们忽略了「当 `nums` 存在重复元素,且该元素作为子数组最大值时,最远左右端点的边界越过重复元素时,导致重复统计子数组」的问题。**
50+
51+
我们不失一般性的举个 🌰 来理解(下图):
52+
53+
![WechatIMG2612.png](https://pic.leetcode.cn/1669252798-kJygAC-WechatIMG2612.png)
54+
55+
为了消除这种重复统计,我们可以将「最远左右边界」的一端,从「严格小于」调整为「小于等于」,从而实现半开半闭的效果。
56+
57+
Java 代码:
58+
```Java
59+
class Solution {
60+
public int numSubarrayBoundedMax(int[] nums, int a, int b) {
61+
int n = nums.length, ans = 0;
62+
int[] l = new int[n + 10], r = new int[n + 10];
63+
Arrays.fill(l, -1); Arrays.fill(r, n);
64+
Deque<Integer> d = new ArrayDeque<>();
65+
for (int i = 0; i < n; i++) {
66+
while (!d.isEmpty() && nums[d.peekLast()] < nums[i]) r[d.pollLast()] = i;
67+
d.addLast(i);
68+
}
69+
d.clear();
70+
for (int i = n - 1; i >= 0; i--) {
71+
while (!d.isEmpty() && nums[d.peekLast()] <= nums[i]) l[d.pollLast()] = i;
72+
d.addLast(i);
73+
}
74+
for (int i = 0; i < n; i++) {
75+
if (nums[i] < a || nums[i] > b) continue;
76+
ans += (i - l[i]) * (r[i] - i);
77+
}
78+
return ans;
79+
}
80+
}
81+
```
82+
TypeScript 代码:
83+
```TypeScript
84+
function numSubarrayBoundedMax(nums: number[], a: number, b: number): number {
85+
let n = nums.length, ans = 0
86+
const l = new Array<number>(n).fill(-1), r = new Array<number>(n).fill(n)
87+
let stk = new Array<number>()
88+
for (let i = 0; i < n; i++) {
89+
while (stk.length > 0 && nums[stk[stk.length - 1]] < nums[i]) r[stk.pop()] = i
90+
stk.push(i)
91+
}
92+
stk = new Array<number>()
93+
for (let i = n - 1; i >= 0; i--) {
94+
while (stk.length > 0 && nums[stk[stk.length - 1]] <= nums[i]) l[stk.pop()] = i
95+
stk.push(i)
96+
}
97+
for (let i = 0; i < n; i++) {
98+
if (nums[i] < a || nums[i] > b) continue
99+
ans += (i - l[i]) * (r[i] - i)
100+
}
101+
return ans
102+
}
103+
```
104+
Python3 代码:
105+
```Python
106+
class Solution:
107+
def numSubarrayBoundedMax(self, nums: List[int], a: int, b: int) -> int:
108+
n, ans = len(nums), 0
109+
l, r = [-1] * n, [n] * n
110+
stk = []
111+
for i in range(n):
112+
while stk and nums[stk[-1]] < nums[i]:
113+
r[stk.pop()] = i
114+
stk.append(i)
115+
stk = []
116+
for i in range(n - 1, -1, -1):
117+
while stk and nums[stk[-1]] <= nums[i]:
118+
l[stk.pop()] = i
119+
stk.append(i)
120+
for i in range(n):
121+
if a <= nums[i] <= b:
122+
ans += (i - l[i]) * (r[i] - i)
123+
return ans
124+
125+
```
126+
* 时间复杂度:$O(n)$
127+
* 空间复杂度:$O(n)$
128+
129+
---
130+
131+
### 模拟
132+
133+
除了统计「每个 $nums[i]$ 作为子数组最大值时,所能贡献的子数组个数」以外,我们还可以统计「每个 $nums[i]$ 作为子数组右端点时,所能贡献的子数组个数」。
134+
135+
具体的,我们从前往后处理每个 $nums[i]$,并统计其作为子数组右端点时,所能贡献的子数组个数。同时使用变量 `j``k` 分别记录最近一次满足「$nums[i]$ 范围落在 $[a, b]$ 之间」以及「$nums[i]$ 数值大于 $b$」的下标位置。
136+
137+
遍历过程中根据 $nums[i]$ 与规定范围 $[a, b]$ 之间的关系进行分情况讨论:
138+
139+
* $nums[i]$ 大于 $b$,$nums[i]$ 作为右端点,必不可能贡献合法子数组。更新 `k`
140+
* $nums[i]$ 小于 $a$,此时 $nums[i]$ 想作为右端点的话,子数组必须有其他满足「范围落在 $[a, b]$ 之间」的其他数,而最近一个满足要求的位置为 $j$,若有 $j > k$,说明范围在 $(k, j]$ 均能作为子数组的左端点,累加方案数 $j - k$;若有 $j < k$,说明我们无法找到任何一个左端点,使得形成的子数组满足要求(要么最值不在 $[a, b]$ 范围内,要么有 $[a, b]$ 范围内的数,但最大值又大于 `b` 值);
141+
* $nums[i]$ 落在范围 $[a, b]$,此时 $nums[i]$ 想作为右端点的话,只需要找到左边第一个数值大于 $b$ 的数值即可(即变量 `k`),累加方案数 $i - k$。更新 `j`
142+
143+
Java 代码:
144+
```Java
145+
class Solution {
146+
public int numSubarrayBoundedMax(int[] nums, int a, int b) {
147+
int n = nums.length, ans = 0;
148+
for (int i = 0, j = -1, k = -1; i < n; i++) {
149+
if (nums[i] > b) {
150+
k = i;
151+
} else {
152+
if (nums[i] < a) {
153+
if (j > k) ans += j - k;
154+
} else {
155+
ans += i - k;
156+
j = i;
157+
}
158+
}
159+
}
160+
return ans;
161+
}
162+
}
163+
```
164+
TypeScript 代码:
165+
```TypeScript
166+
function numSubarrayBoundedMax(nums: number[], a: number, b: number): number {
167+
let n = nums.length, ans = 0
168+
for (let i = 0, j = -1, k = -1; i < n; i++) {
169+
if (nums[i] > b) {
170+
k = i
171+
} else {
172+
if (nums[i] < a) {
173+
if (j > k) ans += j - k
174+
} else {
175+
ans += i - k
176+
j = i
177+
}
178+
}
179+
}
180+
return ans
181+
}
182+
```
183+
Python3 代码:
184+
```Python
185+
class Solution:
186+
def numSubarrayBoundedMax(self, nums: List[int], a: int, b: int) -> int:
187+
n, ans = len(nums), 0
188+
j, k = -1, -1
189+
for i in range(n):
190+
if nums[i] > b:
191+
k = i
192+
else:
193+
if nums[i] < a:
194+
ans += j - k if j > k else 0
195+
else:
196+
ans += i - k
197+
j = i
198+
return ans
199+
```
200+
* 时间复杂度:$O(n)$
201+
* 空间复杂度:$O(1)$
202+
203+
---
204+
205+
### 最后
206+
207+
这是我们「刷穿 LeetCode」系列文章的第 `No.795` 篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。
208+
209+
在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。
210+
211+
为了方便各位同学能够电脑上进行调试和提交代码,我建立了相关的仓库:https://github.com/SharingSource/LogicStack-LeetCode
212+
213+
在仓库地址里,你可以看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其他优选题解。
214+

0 commit comments

Comments
 (0)