当前位置 博文首页 > Liu,:Leetcode——H指数

    Liu,:Leetcode——H指数

    作者:[db:作者] 时间:2021-07-20 09:45

    1. 题目

    给定一位研究者论文被引用次数的数组(被引用次数是非负整数)。编写一个方法,计算出研究者的 h 指数。

    h 指数的定义:h 代表“高引用次数”(high citations),一名科研人员的 h 指数是指他(她)的 (N 篇论文中)总共有 h 篇论文分别被引用了至少 h 次。且其余的 N - h 篇论文每篇被引用次数 不超过 h 次。

    例如:某人的 h 指数是 20,这表示他已发表的论文中,每篇被引用了至少 20 次的论文总共有 20 篇。

    在这里插入图片描述

    2. 题解

    解法一:

    排序:

    • 在遍历过程中找到当前值 citations[i]>h,则说明我们找到了一篇被引用了至少 h+1 次的论文
    • 所以将现有的 h 值加 1。继续遍历直到 h 无法继续增大。最后返回 h 作为最终答案。
    class Solution {
        public int hIndex(int[] citations) {
            Arrays.sort(citations);
            int h = 0, i = citations.length - 1; 
            while (i >= 0 && citations[i] > h) {	//判断当前文章引用次数是不是大于h
                h++; 		//找到h篇被引用至少h次以上的论文
                i--;
            }
            return h;
        }
    }
    
    

    解法二:

    计数排序:

    • 最终的时间复杂度与排序算法的时间复杂度有关,所以我们可以使用计数排序算法,新建并维护一个数组counter 用来记录当前引用次数的论文有几篇。
    • 根据定义,我们可以发现H 指数不可能大于总的论文发表数,所以对于引用次数超过论文发表数的情况,我们可以将其按照总的论文发表数来计算即可。这样我们可以限制参与排序的数的大小为[0,n](其中 n为总的论文发表数),使得计数排序的时间复杂度降低到 O(n)O(n)。
    • 最后我们可以从后向前遍历数组 counter,对于每个 0≤i≤n,在数组 counter 中得到大于或等于当前引用次数 i 的总论文数。当我们找到一个H 指数时跳出循环,并返回结果。
    public class Solution {
        public int hIndex(int[] citations) {
            int n = citations.length, tot = 0;
            int[] counter = new int[n + 1];
            for (int i = 0; i < n; i++) {
                if (citations[i] >= n) {
                    counter[n]++;
                } else {
                    counter[citations[i]]++;
                }
            }
            for (int i = n; i >= 0; i--) {
                tot += counter[i];			//tot = 引用次数为i以上的有多少篇
                if (tot >= i) {				// h tot篇论文分别被引用了至少 i 次
                    return i;
                }
            }
            return 0;
        }
    }
    

    解法三:

    二分查找:

    • 先排序,然后
    • 设查找范围的初始左边界 left 为 00 初始右边界 right 为n?1,其中 n 为数组citations 的长度。每次在查找范围内取中点 mid,则有 n?mid 篇论文被引用了至少]citations[mid] 次。
    • 如果在查找过程中满足 citations[mid]≥n?mid,则移动右边界right,否则移动左边界 left。
    class Solution {
        public int hIndex(int[] citations) {
            Arrays.sort(citations);
            int n = citations.length;
            int left = 0, right = n - 1;
            while (left <= right) {
                int mid = left + (right - left) / 2;
                if (citations[mid] >= n - mid) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            }
            return n - left;
        }
    }
    
    
    cs
    下一篇:没有了