LeetCode------H-Index

这里写图片描述

先排序
    // H-Index
    // Time complexity: O(nlogn), Space complexity: O(1)    
    public int hIndex(int[] citations) {
        //使用sort对数组从小到大排序
        Arrays.sort(citations);
        //翻转数组,使数组从大到小排序
        reverse(citations);
        for (int i = 0; i < citations.length; ++i) {
            //当出现当前文章数(即下标+1) 等于值本身,则返回当前文章数作为 h-index;
            if (i + 1 == citations[i]) return i+1;
            //当出现当前文章数小于值本身,则返回当前文章数-1作为h-index
            if (i + 1 > citations[i]) return i;
        } 
        return citations.length;
    } 
    //反转数组
    private static void reverse(int[] nums) {
        int left = 0;
        int right = nums.length - 1;
        while (left < right) {
            final int tmp = nums[left];
            nums[left] = nums[right];
            nums[right] = tmp;
            ++left;
            --right;
        }
    }
计数排序思想
    //使用计数排序
    public int hIndex2(int citations[]) {
        final int n = citations.length+1;
        final int[] count = new int[n+1];
        //遍历citations数组
        for(int x : citations) {
            //计数:如果x大于n则都记为n,使count[n]+1
            ++count[x>n?n:x];
        }
        int sum = 0;
        for(int i = n;i>0;i--) {
            //引用次数从高到低,并将每个值出现的次数累加
            sum += count[i];
            //当累加值第一次大于下标时返回i
            if(sum>=i) {
                return i;
            }
        }
        return 0;
    }

例如数组arr[] = {3,6,0,5,2}时的计数情况:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值