class Solution {
public:
int hIndex(vector<int>& citations) {
int l = 0, r = citations.size()+1; //至于为什么要加1呢,我们要保证第一次的r不是我们要的那就是+1呗~~让他大!!!
while (l < r) {
int mid = (l+r)/2;
int cnt = 0;
for (int& i : citations) {
if (i >= mid) {
cnt ++;
}
}
if (cnt < mid) {
r = mid; //因为在这里mid太大了 本来应该r=mid-1,我们还是保留了。而下面的left可能导致l=r,此时r不是我们要的所以l要减少1呢
} else {
l = mid + 1;//因为我要寻找最大的L是多少,
}
}
return l - 1;
}
};
另一种二分查找,考虑到还是想保持逻辑运算的规则,但是这边逻辑运算的话 r是必须减少,我们要找到最大的一个符合条件得值,我们担心 l 和 r相差一个单位的时候,陷入死循环,mid=l,而且也是走下面的道路,怎么办?那就是l+r+1这样能帮助我们把mid拉到right地方!
class Solution {
public:
int hIndex(vector<int>& cit) {
int n=cit.size();
int l = 0, r = n;
while(l < r){
int mid = (l+r+1)/2; //+1是为了避免当n=1时,程序陷入死循环
int t = 0;
for(auto x:cit){
if(x >= mid) t ++;
}
if(t < mid) r = mid - 1; //此时答案不满足,收缩右边界
else l = mid; //此时满足,扩大左边界
}
return l;
}
};
————————————————————————————————————————————
除了二分法,我们可以用排序的方式,索引值H一开始给0,只要找到比我索引值大的就+1 。
至少满足N个论文索引值是大于等于N的,所以就是看当h=1是否满足满足,当h=2是否满足 满足就给他继续找找找。一开始是0
class Solution {
public:
int hIndex(vector<int>& citations) {
sort(citations.begin(), citations.end());
int h = 0, i = citations.size() - 1;
while (i >= 0 && citations[i] > h) {
h++;
i--;
}
return h;
}
};
或者计数排序
class Solution {
public:
int hIndex(vector<int>& citations) {
int n = citations.size(), tot = 0;
vector<int> counter(n + 1);
for (int i = 0; i < n; i++) {
if (citations[i] >= n) {
counter[n]++;
} else {
counter[citations[i]]++;
}
}
for (int i = n; i >= 0; i--) {
tot += counter[i];
if (tot >= i) {
return i;
}
}
return 0;
}
};