Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?
s思路:
1. 排过序的,就更好办了!
2. 不对,肯定不是o(n)这么便宜的事。排序,又都是正数,还不得用binary search啊。绝了!
3. debug疑问:最后返回的时候是n-l还是n-r?
s这是千年老问题了,返回到底返回啥一定要根据问题来定,不能一概而论。比如这里,while运行到边界的时候,l==r==m,此时如果if(citations[m]>n-m),表示后面的长度比citations[m]小,那么取长度就可以了,即:n-m或n-l,注意不能取n-r,因为最后一步r=m-1;如果if(citations[m]
class Solution {
public:
int hIndex(vector<int>& citations) {
//
int n=citations.size();
if(n==0) return 0;
int l=0,r=n-1;
while(l<=r){
int m=l+(r-l)/2;
if(citations[m]==n-m) return citations[m];
if(citations[m]>n-m)
r=m-1;
else
l=m+1;
}
return n-l;//bug:最后返回的时候是n-l还是n-r?
}
};