LeetCode 1608. Special Array With X Elements Greater Than or Equal X
考点 | 难度 |
---|---|
Sorting | Easy |
题目
You are given an array nums
of non-negative integers. nums
is considered special if there exists a number x such that there are exactly x numbers in nums
that are greater than or equal to x.
Notice that x does not have to be an element in nums
.
Return x if the array is special, otherwise, return -1. It can be proven that if nums
is special, the value for x is unique.
思路
先对array排序,再依次检查每个可能的x值。对于每个x值,先用binary search找到array里第一个满足nums[index]>=x
的index。在整个array里大于等于nums[index]
的数一共有len-index
个。判断len-index
是