2024/10/28 灵茶题单 不定长滑动窗口
This commit is contained in:
parent
4f174d3f05
commit
43eafe6a62
|
@ -48,6 +48,36 @@ public class Num2831 {
|
||||||
return res;
|
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
|
@Test
|
||||||
public void test() {
|
public void test() {
|
||||||
List<Integer> objects = new ArrayList<>();
|
List<Integer> objects = new ArrayList<>();
|
||||||
|
|
Loading…
Reference in New Issue