[Java][Leetcode middle] 274. H 指数

自己想的,利用排序

一开始死活想不到,看了题目标签的排序才想到的

现将数组升序,然后比较下标。

	public int hIndex1(int[] citations) {
         int h = 0;
         Arrays.sort(citations);
         for (int i = 0; i < citations.length; i++) {
             if (citations[i] >= citations.length-i) {
                  h = citations.length-i;
                  break;
             }
         }
         return h;
    }

基于计数,官方解析

定义一个数组counter[i],用于记录引用次数为i的论文篇数(注意指数最大为发布的文章数,须特殊处理)
倒序循环,只要找出满足的情况位置。

        int len = citations.length;
        int [] counter = new int[len+1];
        int total = 0;
        for (int i = 0; i < len; i++) {
            if(citations[i] >= len){
                counter[len]++;
            }else{
                counter[citations[i]]++;
            }
        }
        for(int i = len; i>=0;i++){
            total += counter[i];
            if(total>=i){
                return i;
            }
        }
        return 0;

利用二分查找

定义left和right 分别为h指数的最大最小值(0,n)
定义mid,并统计大于等于mid的文章数cnt
如果小于cnt,说明h在mid左边,反之在右边

    public int hIndex3(int[] citations) {
        int left = 0, right = citations.length;
        int mid = 0;
        int i;
        int cnt = 0;
        while (left < right) {
            mid  = (left + right + 1) >> 1;
            cnt = 0;
            for( i = 0;i < citations.length;i++){
                if(citations[i] >= mid){
                    cnt++;
                }
            }
            if(cnt>=mid){
                left = mid;
            }else {
                right = mid - 1;
            }
        }
        return left;
    }

你可能感兴趣的:(java,leetcode)