3289. The Two Sneaky Numbers of Digit ville #2365
-
|
Topics: In the town of Digitville, there was a list of numbers called As the town detective, your task is to find these two sneaky numbers. Return an array of size two containing the two numbers (in any order), so peace can return to Digitville. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to find the two numbers that appear twice in an array that should contain each number from 0 to n-1 exactly once. Let me analyze the approaches: Approach 1: Using a Frequency Array
Approach 2: Using Sum and Mathematical Properties
Approach 3: Using Sorting
Let's implement this solution in PHP: 3289. The Two Sneaky Numbers of Digit ville <?php
/**
* @param Integer[] $nums
* @return Integer[]
*/
function getSneakyNumbers($nums) {
$n = count($nums) - 2;
$freq = array_fill(0, $n, 0);
$result = [];
// Count frequency of each number
foreach ($nums as $num) {
$freq[$num]++;
}
// Find numbers that appear twice
for ($i = 0; $i < $n; $i++) {
if ($freq[$i] == 2) {
$result[] = $i;
}
}
return $result;
}
// Test cases
// Example 1
$nums = [0, 1, 1, 0];
print_r(getSneakyNumbers($nums)); // [0, 1]
// Example 2
$nums = [0, 3, 2, 1, 3, 2];
print_r(getSneakyNumbers($nums)); // [2, 3]
// Example 3
$nums = [7, 1, 5, 4, 3, 4, 6, 0, 9, 5, 8, 2];
print_r(getSneakyNumbers($nums)); // [4, 5]
?>Explanation:
Example walkthrough with nums = [0,1,1,0]:
This solution is efficient with O(n) time complexity and O(n) space complexity, which is optimal for the given constraints (n ≤ 100). |
Beta Was this translation helpful? Give feedback.
We need to find the two numbers that appear twice in an array that should contain each number from 0 to n-1 exactly once.
Let me analyze the approaches:
Approach 1: Using a Frequency Array
Approach 2: Using Sum and Mathematical Properties
Approach 3: Using Sorting
Let's…