Problem
Notes
这个题的意思是,给一个具有n个非负数的数组,找出最大的h,使得这个数组中h个元素>=h,剩下的n-h个元素<=h。注意两边都有等号(开始做的时候看漏了一个等号,还感觉题目出错了…)
只想到快排顺序查找的方法。时间复杂度就是快排的o(nlogn),空间复杂度o(1)。
遍历时的条件,自己写一下样例就明白了。
Codes
class Solution {
public:
int hIndex(vector<int>& citations) {
int len=citations.size();
if(!len) return 0;
sort(citations.begin(),citations.end());
int ans;
for(int h=1;h<=len;++h)
{
if(citations[len-h]<=h)
return citations[len-h]==h?h:h-1;
else
ans=h;
}
return ans;
}
};