Java經典算法:citations數組按升序排序

如果citations數組按升序排序怎麼辦?您可以優化算法嗎?
給定數組已排序,我們應該使用二進制搜索。
int hIndex(int[] citations) {
int len = citations.length;

if (len == 0) {
    return 0;
}

if (len == 1) {
    if (citations[0] == 0) {
        return 0;
    } else {
        return 1;
    }
}

int i = 0;
int j = len - 1;
while (i < j) {
    int m = i + (j - i + 1) / 2;
    if (citations[m] > len - m) {
        j = m - 1;
    } else {
        i = m;
    }
}

if (citations[j] > len - j) {
    return len;
}

if (citations[j] == len - j) {
    return len - j;
} else {
    return len - j - 1;
}}

最後,開發這麼多年我也總結了一套學習Java的資料與面試題,如果你在技術上面想提升自己的話,可以關注我,私信發送領取資料或者在評論區留下自己的聯繫方式,有時間記得幫我點下轉發讓跟多的人看到哦。在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章