Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode 2444. Count Subarrays With Fixed Bounds #220

Open
Woodyiiiiiii opened this issue Mar 7, 2023 · 0 comments
Open

Leetcode 2444. Count Subarrays With Fixed Bounds #220

Woodyiiiiiii opened this issue Mar 7, 2023 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

Woodyiiiiiii commented Mar 7, 2023

同一类型题目:

这一类型的题有点像滑动窗口,但不同的是窗口里可以呈辐射状,包括一些不满足条件的元素,题目最终要求满足条件的子数组数目。(Array/Sliding Window/Queue)

重点在于如何计算:三个点,起点、左端点和右端点。以最左端点为基准,右边端点每次延伸都加上左端点到起点的距离。如何计算。

class Solution {
    public long countSubarrays(int[] nums, int minK, int maxK) {
        int lb = -1, lmin = -1, lmax = -1;
        int n = nums.length;
        long count=0;

        for (int i=0; i<n; i++) {
            if (nums[i] >= minK && nums[i] <= maxK) {
                lmin = (nums[i] == minK) ? i:lmin;
                lmax = (nums[i] == maxK) ? i:lmax;
                count+= Math.max(0, Math.min(lmin, lmax) - lb);
            } else {
                lb = i;
                lmin = -1;
                lmax = -1;
            }
        }

        return count;
    }
}
class Solution {
    public int numberOfSubarrays(int[] nums, int k) {
        int cnt = 0, ans = 0;
        int l = -1;
        int ll = -1;
        Queue<Integer> queue = new ArrayDeque<>();
        for (int i = 0; i < nums.length; ++i) {
            if (nums[i] % 2 != 0) {
                queue.add(i);
                if (l == -1) {
                    l = i;
                }
                ++cnt;
                if (cnt > k) {
                    ll = l;
                    cnt--;
                    queue.poll();
                    l = queue.isEmpty() ? -1 : queue.peek();
                    if (cnt == k) {
                        ans += Math.max(0, l - ll);
                    }
                } else if (cnt == k) {
                    ans += Math.max(0, l - ll);
                }
            } else {
                if (cnt == k) {
                    ans += l - ll;
                }
            }
        }
        return ans;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant