2024/11/6 灵茶题单 滑动窗口 恰好型滑动窗口

This commit is contained in:
Cool 2024-11-07 17:57:46 +08:00
parent b731afa787
commit c2a1123a7e
1 changed files with 58 additions and 0 deletions

View File

@ -0,0 +1,58 @@
package com.cool.ling_cha_mount.sliding_windows;
/**
* @author : Cool
* @date: 2024/11/07
* 1248. 统计优美子数组
*/
public class Num1248 {
/**
* @Author Cool
* @Date 17:43 2024/11/7
* 前缀和
**/
public int numberOfSubarrays1(int[] nums, int k) {
int res = 0;
int count=0;
int[] arr = new int[nums.length + 1];
arr[0]=1;
for(int num:nums){
count+=num&1;
arr[count]++;
if(count>=k){
res+=arr[count-k];
}
}
return res;
}
/**
* @Author Cool
* @Date 17:56 2024/11/7
* 滑动窗口
**/
public int numberOfSubarrays(int[] nums, int k) {
int left = 0;
int right = 0;
int count = 0;
int res = 0;
while (right < nums.length) {
count += nums[right++] & 1;
if (count >= k) {
int leftCount = 0;
while ((nums[left] & 1) == 0) {
leftCount++;
left++;
}
int rightCount = 0;
while (right < nums.length && (nums[right] & 1) == 0) {
right++;
rightCount++;
}
res += (rightCount + 1) * (leftCount + 1);
count--;
left++;
}
}
return res;
}
}