面试经典 150 题 (十二)

排序,i代表至少发表的论文数量
时间复杂度:O(nlogn)
空间复杂度:O(logn)

class Solution {
    public int hIndex(int[] citations) {
        // 0 1 3 5 6
        int length = citations.length;
        Arrays.sort(citations);
        int h = 0;
        for (int i = 1; i <= length; i++){
            if (citations[length - i] >= i) {
                h = i;
                continue;
            }else{
                break;
            }
        }
        return h;
    }
}

计数排序
时间复杂度: O(n)
空间复杂度: O(n)

class Solution {
    public int hIndex(int[] citations) {
        // 0 1 3 5 6
        int length = citations.length;
        int[] counter = new int[length + 1]; //[0,length]
        //引用数量大于等于h的论文数量都被记录在counter[length]中
        for(int i = 0;i < length;i++){
            if(citations[i] >= length) counter[length]++;
            else{
                counter[citations[i]]++;
            }
        }
        int total = 0;
        //i代表了最少发表的论文数量
        for(int i = length; i >=0; i--){
            total += counter[i];
            if(total >= i)
                return i;
        }
        return 0;
    }
}
posted @ 2024-02-07 11:14  破忒头头  阅读(19)  评论(0)    收藏  举报