Parcourir la source

#feat:leetcode p128题题解

yangyi il y a 2 semaines
Parent
commit
3ed0b3cad0
2 fichiers modifiés avec 86 ajouts et 0 suppressions
  1. 40 0
      src/leetcode/p128/Solution.java
  2. 46 0
      src/leetcode/p128/SolutionTest.java

+ 40 - 0
src/leetcode/p128/Solution.java

@@ -0,0 +1,40 @@
+package leetcode.p128;
+
+import java.util.HashSet;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: Solution
+ * @Author: 杨逸
+ * @Data:2026/3/8 17:21
+ * @Description: https://leetcode.cn/problems/longest-consecutive-sequence/description/
+ * 128. 最长连续序列
+ */
+public class Solution {
+    public int longestConsecutive(int[] nums) {
+        /**
+         * 1.哈希表记录出现过的数字
+         * 2.遍历哈希表,找到 x,如果 x-1 不存在,则从 x 开始计算连续序列长度(确保以x开始计算一定是算出最长的子序列)
+         * 3.计算最长序列长度
+         */
+        HashSet<Integer> set = new HashSet<>();
+        int ans = 0;
+        for (int num : nums) {
+            if (!set.contains(num)) {
+                set.add(num);
+            }
+        }
+        for (Integer x : set) {
+            if (!set.contains(x-1)) {
+               int count = 1;
+               int current = x;
+               while (set.contains(current+1)) {
+                   count++;
+                   current++;
+               }
+               ans = Math.max(ans,count);
+            }
+        }
+        return ans;
+    }
+}

+ 46 - 0
src/leetcode/p128/SolutionTest.java

@@ -0,0 +1,46 @@
+package leetcode.p128;
+
+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:27
+ * @Description:
+ */
+@RunWith(Parameterized.class)
+public class SolutionTest {
+    public static final Solution solution = new Solution();
+    private int[] nums;
+    private int expected;
+
+    public SolutionTest(int[] nums, int expected) {
+        this.nums = nums;
+        this.expected = expected;
+    }
+    @Parameterized.Parameters
+    public static Collection<Object[]> data() {
+        return Arrays.asList(new Object[][]{
+                {new int[]{100,4,200,1,3,2},4},
+                {new int[]{0,3,7,2,5,8,4,6,0,1},9},
+                {new int[]{0,3,7,2,5,8,4,6,0,1},9},
+                {new int[]{1,0,1,2},3},
+                {new int[]{1,100},1},
+                {new int[]{0,1,2,4,8,5,6,7,9,3,55,88,77,99,999999999},10},
+        });
+    }
+
+    @Test(timeout = 1000L)
+    public void longestConsecutive() {
+        int result = solution.longestConsecutive(nums);
+        assertEquals(expected,result);
+    }
+}