275. H-Index II

Follow up for 第274題[H-Index] http://www.itdecent.cn/p/571bf9481ede
What if the citations array is sorted in ascending order? Could you optimize your algorithm?

Solution:Binary Search

思路: 二分長(zhǎng)度查找mid處的citations[mid]是否已經(jīng)可以滿足條件(citations大于它的(它的右邊)已經(jīng)有citations[mid]個(gè)paper數(shù)量[通過長(zhǎng)度判斷]),滿足的話繼續(xù)往左邊part找,不滿足往右邊part找
[0 2 3 5 6 8]
pattern: 滿足 滿足 滿足 不滿足 不滿足 不滿足
Time Complexity: O(logN) Space Complexity: O(1)

Solution Code:

class Solution {
    public int hIndex(int[] citations) {
        int length = citations.length;
        if(length == 0) return 0;
        if(length == 1) return citations[0] >= 1 ? 1 : 0;
        
        int start = 0, end = length - 1;
        while(start <= end) {
            int mid = start + (end - start) / 2;
            if(citations[mid] == (length - mid)) return citations[mid];
            else if(citations[mid] > (length - mid)) end = mid - 1;
            else start = mid + 1;
        }
        return length - (end + 1); 
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容