From 43eafe6a624a343085f493db3fb3e9091ff6c410 Mon Sep 17 00:00:00 2001 From: Cool <747682928@qq.com> Date: Mon, 28 Oct 2024 19:19:54 +0800 Subject: [PATCH] =?UTF-8?q?2024/10/28=20=E7=81=B5=E8=8C=B6=E9=A2=98?= =?UTF-8?q?=E5=8D=95=20=E4=B8=8D=E5=AE=9A=E9=95=BF=E6=BB=91=E5=8A=A8?= =?UTF-8?q?=E7=AA=97=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../sliding_windows/Num2831.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/main/java/com/cool/ling_cha_mount/sliding_windows/Num2831.java b/src/main/java/com/cool/ling_cha_mount/sliding_windows/Num2831.java index 7846897..5c0af69 100644 --- a/src/main/java/com/cool/ling_cha_mount/sliding_windows/Num2831.java +++ b/src/main/java/com/cool/ling_cha_mount/sliding_windows/Num2831.java @@ -48,6 +48,36 @@ public class Num2831 { return res; } + /** + * @Author Cool + * @Date 19:19 2024/10/28 + * 灵神解法 + **/ + public int longestEqualSubarray1(List nums, int k) { + int n = nums.size(); + List[] 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 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 objects = new ArrayList<>();