1394. Find Lucky Integer in an Array #1890
-
Topics: Given an array of integers Return the largest lucky integer in the array. If there is no lucky integer return 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 largest "lucky integer" in an array. A lucky integer is defined as an integer whose frequency in the array is exactly equal to its value. If no such integer exists, we should return -1. Approach
Let's implement this solution in PHP: 1394. Find Lucky Integer in an Array <?php
/**
* @param Integer[] $arr
* @return Integer
*/
function findLucky($arr) {
$count = array_fill(0, 501, 0);
foreach ($arr as $num) {
$count[$num]++;
}
for ($i = 500; $i >= 1; $i--) {
if ($count[$i] == $i) {
return $i;
}
}
return -1;
}
// Test cases
echo findLucky(array(2,2,3,4)) . "\n"; // Output: 2
echo findLucky(array(1,2,2,3,3,3)) . "\n"; // Output: 3
echo findLucky(array(2,2,2,3,3)) . "\n"; // Output: -1
?> Explanation:
This approach efficiently leverages frequency counting and a reverse iteration to quickly determine the largest lucky integer, ensuring optimal performance given the problem constraints. |
Beta Was this translation helpful? Give feedback.
We need to find the largest "lucky integer" in an array. A lucky integer is defined as an integer whose frequency in the array is exactly equal to its value. If no such integer exists, we should return -1.
Approach