LeetCode 3289: The Two Sneaky Numbers of Digitville
Problem Description
Explanation
To find the two sneaky numbers in the given list, we can use a HashSet to keep track of the numbers we have seen so far. As we iterate through the list, if we encounter a number that is already in the HashSet, that number is one of the sneaky numbers. At the end of the iteration, the two numbers remaining in the HashSet are the two sneaky numbers.
- Time complexity: O(n)
- Space complexity: O(n)
Solutions
import java.util.*;
class Solution {
public int[] findSneakyNumbers(int[] nums) {
Set<Integer> seen = new HashSet<>();
int[] sneakyNumbers = new int[2];
for (int num : nums) {
if (seen.contains(num)) {
if (sneakyNumbers[0] == 0) {
sneakyNumbers[0] = num;
} else {
sneakyNumbers[1] = num;
break;
}
} else {
seen.add(num);
}
}
return sneakyNumbers;
}
}
Loading editor...