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?
}
};