LeetCode-H-Index I & II

先看第一题 array unsorted 

我自己想到的方法是先排序 然后从后面开始找 找到一个数字<它对应的id 就应该返回它上一个数字 具体的id怎样算 见代码 o(nlogn) 时间  o(1)空间

index      0 1 2 3 4 

number  0 1 3 5 6

id           5 4 3 2 1

public class Solution {
    public int hIndex(int[] citations) {
        Arrays.sort(citations);
        for ( int i = citations.length - 1; i >= 0; i --){
            if ( citations[i] < citations.length - i )
                return citations.length - i - 1;
        }
        return citations.length;
    }
    
}

答案中有一个o(n)时间 o(n)空间的

记录一个计数数组 然后从计数数组后面开始累加 

public class Solution {
    public int hIndex(int[] citations) {
        int n = citations.length;
        int [] arr = new int [n + 1];
        for ( int i = 0; i < n; i ++ ){
            if ( citations[i] >= n )
                arr[ n ] ++;
            else
                arr[ citations[i] ] ++;
        }
        int addUp = 0;
        for ( int i = n; i >= 0; i -- ){
            addUp += arr[ i ];
            if ( addUp >= i )
                return i;
        }
        return 0;
    }
}
然后第二题就是给出了sorted array 用binary search更好!!!o(lgn)!!!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值