Bladeren bron

#feat:leetcode p137题题解

yangyi 2 weken geleden
bovenliggende
commit
0a751d3379
2 gewijzigde bestanden met toevoegingen van 74 en 0 verwijderingen
  1. 33 0
      src/leetcode/p137/Solution.java
  2. 41 0
      src/leetcode/p137/SolutionTest.java

+ 33 - 0
src/leetcode/p137/Solution.java

@@ -0,0 +1,33 @@
+package leetcode.p137;
+
+import java.util.HashMap;
+import java.util.Set;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: Solution
+ * @Author: 杨逸
+ * @Data:2026/3/10 11:28
+ * @Description: https://leetcode.cn/problems/single-number-ii/description/
+ * 137. 只出现一次的数字 II
+ */
+public class Solution {
+    public int singleNumber(int[] nums) {
+        return hashSolution(nums);
+    }
+
+    private int hashSolution(int[] nums) {
+        HashMap<Integer, Integer> map = new HashMap<>();
+        for (int num : nums) {
+            Integer count = map.getOrDefault(num, 0);
+            map.put(num, count+1);
+        }
+        Set<Integer> keySet = map.keySet();
+        for (Integer key : keySet) {
+            if (map.get(key) == 1) {
+                return key;
+            }
+        }
+        return -1;
+    }
+}

+ 41 - 0
src/leetcode/p137/SolutionTest.java

@@ -0,0 +1,41 @@
+package leetcode.p137;
+
+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/10 11:31
+ * @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[]{2,2,3,2},3},
+                {new int[]{0,1,0,1,0,1,99},99},
+        });
+    }
+
+    @Test
+    public void singleNumber() {
+        assertEquals(expected,solution.singleNumber(nums));
+    }
+}