diff --git a/src/main/java/com/leetcode/easy/TheTwoSneakyNumbersOfDigitville3289.java b/src/main/java/com/leetcode/easy/TheTwoSneakyNumbersOfDigitville3289.java new file mode 100644 index 0000000..932374d --- /dev/null +++ b/src/main/java/com/leetcode/easy/TheTwoSneakyNumbersOfDigitville3289.java @@ -0,0 +1,34 @@ +// Tags: Array, Hash Set +package com.leetcode.easy; + +import java.util.HashSet; +import java.util.Set; + +public class TheTwoSneakyNumbersOfDigitville3289 { + /** + * Finds the two numbers that appear twice in the array. + *

+ * Time Complexity: O(n) where n is the length of the array. + * We iterate through the array once, and HashSet operations (add, contains) are O(1) on average. + *

+ * Space Complexity: O(n) for the HashSet to store seen numbers. + * In the worst case, we store almost all numbers before finding the duplicates. + */ + public int[] getSneakyNumbers(int[] nums) { + int[] res = new int[2]; + Set seen = new HashSet<>(); + int index = 0; + for (int num : nums) { + if (seen.contains(num)) { + res[index] = num; + if (index == 1) { + break; + } + index++; + } else { + seen.add(num); + } + } + return res; + } +} diff --git a/src/test/java/com/leetcode/easy/TheTwoSneakyNumbersOfDigitville3289Test.java b/src/test/java/com/leetcode/easy/TheTwoSneakyNumbersOfDigitville3289Test.java new file mode 100644 index 0000000..42b6fd8 --- /dev/null +++ b/src/test/java/com/leetcode/easy/TheTwoSneakyNumbersOfDigitville3289Test.java @@ -0,0 +1,50 @@ +package com.leetcode.easy; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; + +public class TheTwoSneakyNumbersOfDigitville3289Test { + private TheTwoSneakyNumbersOfDigitville3289 solution; + + @BeforeEach + void setUp() { + solution = new TheTwoSneakyNumbersOfDigitville3289(); + } + + @Test + void testGetSneakyNumbers_Example1() { + int[] nums = {0, 1, 1, 0}; + int[] expected = {0, 1}; + + int[] result = solution.getSneakyNumbers(nums); + Arrays.sort(result); + + assertArrayEquals(expected, result); + } + + @Test + void testGetSneakyNumbers_Example2() { + int[] nums = {0, 3, 2, 1, 3, 2}; + int[] expected = {2, 3}; + + int[] result = solution.getSneakyNumbers(nums); + Arrays.sort(result); + + assertArrayEquals(expected, result); + } + + @Test + void testGetSneakyNumbers_Example3() { + int[] nums = {7, 1, 5, 4, 3, 4, 6, 0, 9, 5, 8, 2}; + int[] expected = {4, 5}; + + int[] result = solution.getSneakyNumbers(nums); + Arrays.sort(result); + + assertArrayEquals(expected, result); + } +}