add leetcode 1608

This commit is contained in:
sangge-redmi 2024-05-27 13:46:24 +08:00
parent c1a78cca82
commit 90f5acae0f

43
leetcode/1608.py Normal file
View File

@ -0,0 +1,43 @@
from typing import List
class Solution:
def bin_specialArray(self, nums: List[int]) -> int:
nums.sort()
left, right = 0, len(nums)
while left <= right:
mid = (left + right) // 2
count = sum(1 for num in nums if num >= mid)
if count == mid:
return mid
elif count < mid:
right = mid - 1
else:
left = mid + 1
return -1
def specialArray(self, nums: List[int]) -> int:
"""
Determines if there is a special number x in the list such that there are exactly x elements
in the list that are greater than or equal to x.
Args:
nums (List[int]): The list of non-negative integers.
Returns:
int: The special number x, or -1 if no such number exists.
"""
nums.sort()
n = len(nums)
for x in range(1, n + 1):
# Count how many numbers are greater than or equal to x
count = sum(1 for num in nums if num >= x)
if count == x:
return x
return -1