题目
思路
- 二分查找,右边区间需要满足条件
nums[i] >= h
- 寻找右边区间的左端点即可
-
代码
class Solution {
public:
// 排序之后,右边区间满足了条件:nums[i] >= h
int hIndex(vector<int>& citations) {
int n = citations.size();
int left = 0, right = n - 1;
while (left < right) {
int mid = (left + right) / 2;
if (citations[mid] >= (n - 1) - mid + 1) {
right = mid;
} else {
left = mid + 1;
}
}
// 右边区间的左端点 == n - 1
if (citations[left] == 0) {
return 0;
} else {
return (n - 1) - left + 1;
}
}
};