Follow up for H-Index: What if the citations
array is sorted in ascending order? Could you optimize your algorithm?
接上一篇,数组升序排列。
一看就是二分,需要注意边界,仔细想想。
代码语言:javascript复制class Solution {
public:
int hIndex(vector<int>& citations) {
int mid = -1, l = 0, r = citations.size()-1;
while(l <= r)
{
mid = (l r) >> 1;
if(citations.size() - mid == citations[mid]) return citations[mid];
else if(citations.size() - mid > citations[mid]) l = mid 1;
else r = mid - 1;
}
return citations.size() - r - 1;
}
};