You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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;
}
}
同一类型题目:
这一类型的题有点像滑动窗口,但不同的是窗口里可以呈辐射状,包括一些不满足条件的元素,题目最终要求满足条件的子数组数目。(Array/Sliding Window/Queue)
重点在于如何计算:三个点,起点、左端点和右端点。以最左端点为基准,右边端点每次延伸都加上左端点到起点的距离。如何计算。
The text was updated successfully, but these errors were encountered: