搜索

795. 区间子数组个数


发布时间: 2022-11-24 19:14:01    浏览次数:72 次

795. 区间子数组个数

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;
    }

    
}
免责声明 795. 区间子数组个数,资源类别:文本, 浏览次数:72 次, 文件大小:-- , 由本站蜘蛛搜索收录2022-11-24 07:14:01。此页面由程序自动采集,只作交流和学习使用,本站不储存任何资源文件,如有侵权内容请联系我们举报删除, 感谢您对本站的支持。 原文链接:https://www.cnblogs.com/eiffelzero/p/16922929.html