1608. Special Array With X Elements Greater Than or Equal X #1954
-
Topics: You are given an array Notice that Return Example 1:
Example 2:
Example 3:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find a number Approach
Let's implement this solution in PHP: 1608. Special Array With X Elements Greater Than or Equal X <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function specialArray($nums) {
sort($nums);
$n = count($nums);
if ($nums[0] >= $n) {
return $n;
}
for ($x = 1; $x < $n; $x++) {
if ($nums[$n - $x] >= $x && $nums[$n - $x - 1] < $x) {
return $x;
}
}
return -1;
}
// Test cases
print_r(specialArray([3, 5])); // Output: 2
print_r(specialArray([0, 0])); // Output: -1
print_r(specialArray([0, 4, 3, 0, 4])); // Output: 3
?> Explanation:
This approach efficiently checks possible values of |
Beta Was this translation helpful? Give feedback.
We need to find a number
x
such that there are exactlyx
numbers in the array that are greater than or equal tox
. The solution involves sorting the array and then efficiently checking possible values ofx
using the sorted properties of the array.Approach
x
.n
), thenx = n
is the solution. This is because all elements in the array are at leastn
, so there are exactlyn
elements greater than or equal ton
.