【力扣刷题】子数组 题单

  • 795. 区间子数组个数
  • 2444. 统计定界子数组的数目

795. 区间子数组个数

class Solution {
public:
    int numSubarrayBoundedMax(vector& nums, int left, int right) {
        // 贡献法:考虑子数组[l, r] 的个数 = r - l + 1, 然后考虑当 l 固定时,r 能到哪【nums[i] >= left && nums[i] <= right】
        // from 灵神:https://leetcode.cn/problems/number-of-subarrays-with-bounded-maximum/solutions/1988198/tu-jie-yi-ci-bian-li-jian-ji-xie-fa-pyth-n75l/
        int n = nums.size();
        int ans = 0;
        int l = 0, r = -1;
        for(int i = 0;i < n;i ++ )
        {
            if(nums[i] >= left && nums[i] <= right) r = i; // 当前右端点可行
            if(nums[i] > right) l = i + 1, r = -1; // l 直接跳到i + 1
            if(r != -1) ans += r - l + 1; // l, r 都满足条件的端点 取值可能
        }
        return ans;
    }
};

2444. 统计定界子数组的数目

class Solution {
public:
    long long countSubarrays(vector& nums, int minK, int maxK) {
        /*
            同样考虑子数组[l, r] 在哪里
            r = min(min_i, max_i), l = i0 + 1【i0为不符合范围的数的下标】
            个数 = r - l + 1 = min(min_i, max_i) - i0, 

            from 灵神:https://leetcode.cn/problems/count-subarrays-with-fixed-bounds/solutions/1895713/jian-ji-xie-fa-pythonjavacgo-by-endlessc-gag2/
        */
        typedef long long LL;
        LL ans = 0;
        int min_i = -1, max_i = -1, i0 = -1;
        for(int i = 0;i < nums.size();i ++ ){
            if(nums[i] == minK) min_i = i;
            if(nums[i] == maxK) max_i = i;

            if(nums[i] < minK || nums[i] > maxK) i0 = i;
            ans += max(min(min_i, max_i) - i0, 0);
        }
        return ans;
    }
};

你可能感兴趣的:(【力扣,刷题】,leetcode,算法)