# 2444. Count Subarrays With Fixed Bounds ###### tags: `Leetcode` `Hard` `Sliding Window` Link: https://leetcode.com/problems/count-subarrays-with-fixed-bounds/description/ ## 思路 sliding window里面放所有在```[minK, maxK]```里面的value 如果新加进来的value不在范围里 那我们就需要挪动左指针 到它的下一个位置 每次移动右指针 我们需要更新```lastMin```和```lastMax```(最后一次出现```minK```和```maxK```的地方) 如果有一个还没出现 就说明以右指针做右端点的window目前没有一个能作为答案 如果都出现了 那么```[left:min(lastMin, lastMax)]```都可以作为左端点 ## Code ```java= class Solution { public long countSubarrays(int[] nums, int minK, int maxK) { int left = 0, right = 0; int lastMin = -1, lastMax = -1; int n = nums.length; long res = 0L; while(right<n){ if(nums[right]<minK || nums[right]>maxK){ lastMin = -1; lastMax = -1; left = right+1; } if(nums[right]==minK) lastMin = right; if(nums[right]==maxK) lastMax = right; if(lastMin!=-1 && lastMax!=-1) res += Math.min(lastMin, lastMax)-left+1; right++; } return res; } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up