275. H-Index II

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?
    }
};
發佈了270 篇原創文章 · 獲贊 4 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章