yangyi 2 недель назад
Родитель
Сommit
df1b009273
2 измененных файлов с 77 добавлено и 0 удалено
  1. 32 0
      src/leetcode/p219/Solution.java
  2. 45 0
      src/leetcode/p219/SolutionTest.java

+ 32 - 0
src/leetcode/p219/Solution.java

@@ -0,0 +1,32 @@
+package leetcode.p219;
+
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: Solution
+ * @Author: 杨逸
+ * @Data:2026/3/8 16:59
+ * @Description: https://leetcode.cn/problems/contains-duplicate-ii/description/
+ * 219. 存在重复元素 II
+ */
+public class Solution {
+    public boolean containsNearbyDuplicate(int[] nums, int k) {
+        //定长滑动窗口
+        //哈希表维护窗口出现的元素
+        Set<Integer> set = new HashSet<>();
+        for (int i = 0; i < nums.length; i++) {
+            if (i>k) {
+                //有元素离开窗口
+                set.remove(nums[i-k-1]);
+            }
+            //新元素进入窗口
+            if (set.contains(nums[i])) {
+                return true;
+            }
+            set.add(nums[i]);
+        }
+        return false;
+    }
+}

+ 45 - 0
src/leetcode/p219/SolutionTest.java

@@ -0,0 +1,45 @@
+package leetcode.p219;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: SolutionTest
+ * @Author: 杨逸
+ * @Data:2026/3/8 17:02
+ * @Description:
+ */
+@RunWith(Parameterized.class)
+public class SolutionTest {
+    public static final Solution solution = new Solution();
+    private int[] nums;
+    private int k;
+    private boolean expected;
+
+    public SolutionTest(int[] nums, int k, boolean expected) {
+        this.nums = nums;
+        this.k = k;
+        this.expected = expected;
+    }
+    @Parameterized.Parameters
+    public static Collection<Object[]> data(){
+        return Arrays.asList(new Object[][]{
+                {new int[]{1,2,3,1},3,true},
+                {new int[]{1,0,1,1},1,true},
+                {new int[]{1,2,3,1,2,3},2,false},
+        });
+    }
+
+    @Test
+    public void containsNearbyDuplicate() {
+        boolean result = solution.containsNearbyDuplicate(nums, k);
+        assertEquals(expected,result);
+    }
+}