[LeetCode] Special Array With X Elements Greater Than or Equal X

1608. Special Array With X Elements Greater Than or Equal X

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int specialArray(vector<int>& A) {
sort(begin(A), end(A));
int l = 0, r = A.size();
while(l <= r) {
int m = l + (r - l) / 2;
int count = end(A) - lower_bound(begin(A), end(A), m);
if(m == count) return m;
if(count > m) l = m + 1;
else r = m - 1;
}
return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/07/PS/LeetCode/special-array-with-x-elements-greater-than-or-equal-x/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.