795. 区间子数组个数

795. 区间子数组个数

题解:

  1. 实现一个函数cal 返回小于等于k的子数组数量
  2. 函数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;
    }
}

题解:单调栈

  1. 求出每个数的作为最大值时的区间
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;
    }

    
}
posted @   Eiffelzero  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
点击右上角即可分享
微信分享提示