795. 区间子数组个数
题解:
- 实现一个函数cal 返回小于等于k的子数组数量
- 函数cal,可以用双指针实现
class Solution {
public int numSubarrayBoundedMax(int[] nums, int left, int right) {
return (int) (cal(nums, right) - cal(nums, left - 1));
}
private long cal(int[] nums, int k) {
int n = nums.length;
long res = 0;
for (int i = 0; i < n; i++) {
if (nums[i] > k) continue;
int j = i + 1;
while (j < nums.length && nums[j] <= k) j++;
int m = j - i;
res += (long)m * (m + 1) / 2;
i = j;
}
return res;
}
}
class Solution {
public int numSubarrayBoundedMax(int[] A, int L, int R) {
return count(A,R)-count(A,L-1);
}
public int count(int[] A, int target){
int cnt = 0; int res = 0;
for(int x : A){
if(x<=target){
cnt++;
}else{
cnt = 0;
}
res += cnt;
}
return res;
}
}
题解:单调栈
- 求出每个数的作为最大值时的区间
class Solution {
public int numSubarrayBoundedMax(int[] A, int L, int R) {
int len = A.length;
Deque<Integer> sta = new ArrayDeque<>();
int[] l = new int[len];
int[] r = new int[len];
for (int i = 0; i < len; i++) {
while (!sta.isEmpty() && A[sta.peekLast()] < A[i]){
int pre = sta.pollLast();
r[pre] = i - 1;
}
l[i] = sta.isEmpty() ? 0 : sta.peekLast()+1;
sta.addLast(i);
}
while (sta.size()>0){
r[sta.pollLast()] = len - 1;
}
int ans = 0;
for (int i = 0; i < len; i++) {
if(A[i] >= L && A[i] <= R){
ans += (r[i] - i + 1) * (i - l[i] + 1) ;
}
}
return ans;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧