2024/10/22 灵茶题单 不定长滑动窗口

This commit is contained in:
Cool 2024-10-22 18:00:48 +08:00
parent 8ad071fec0
commit dd0ceaf000
1 changed files with 33 additions and 0 deletions

View File

@ -0,0 +1,33 @@
package com.cool.ling_cha_mount.sliding_windows;
import java.util.HashMap;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
*
* @Author: Cool
* @Date: 2024/10/22/17:31
* @Description:
*/
public class Num2958 {
public int maxSubarrayLength(int[] nums, int k) {
Map<Integer,Integer> map=new HashMap<>();
int res=0;
int left=0;
for(int i=0;i<nums.length;i++){
Integer old=map.put(nums[i],map.getOrDefault(nums[i],0)+1);
if(old!=null&&old>=k){
res=Math.max(res,i-left);
while(true){
map.put(nums[left],map.get(nums[left])-1);
if(nums[left++]==nums[i]){
break;
}
}
}
}
return Math.max(res,nums.length-left);
}
}