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

This commit is contained in:
Cool 2024-10-28 19:19:54 +08:00
parent 4f174d3f05
commit 43eafe6a62
1 changed files with 30 additions and 0 deletions
src/main/java/com/cool/ling_cha_mount/sliding_windows

View File

@ -48,6 +48,36 @@ public class Num2831 {
return res;
}
/**
* @Author Cool
* @Date 19:19 2024/10/28
* 灵神解法
**/
public int longestEqualSubarray1(List<Integer> nums, int k) {
int n = nums.size();
List<Integer>[] posLists = new ArrayList[n + 1];
Arrays.setAll(posLists, i -> new ArrayList<>());
for (int i = 0; i < n; i++) {
int x = nums.get(i);
posLists[x].add(i - posLists[x].size());
}
int ans = 0;
for (List<Integer> pos : posLists) {
if (pos.size() <= ans) {
continue; // 无法让 ans 变得更大
}
int left = 0;
for (int right = 0; right < pos.size(); right++) {
while (pos.get(right) - pos.get(left) > k) { // 要删除的数太多了
left++;
}
ans = Math.max(ans, right - left + 1);
}
}
return ans;
}
@Test
public void test() {
List<Integer> objects = new ArrayList<>();