本题我用sort的方法解出来了,但是这种方法的时间复杂度是274. H-Index - 图1,所以明显不是最好的,参考了答案,答案用的是一个近似HashMap或者说是bucket sort的方法

    • 定义一个array,arr[i]表示citations里面等于i的数量(最后一个除外)
    • 从后向前遍历,当cnt >= i的是时候,代表有且之后i个元素的值大于等于i,继续遍历的话,只会得到更小的i

    • 时间复杂度:274. H-Index - 图2

    • 空间复杂度:274. H-Index - 图3

    代码如下:

    1. class Solution {
    2. public int hIndex(int[] citations) {
    3. int n = citations.length;
    4. int[] count = new int[n+1];
    5. for (int citation : citations) {
    6. if (citation > citations.length) {
    7. count[n] += 1;
    8. }
    9. else {
    10. count[citation] += 1;
    11. }
    12. }
    13. int cnt = 0;
    14. for (int i = n; i >= 0; --i) {
    15. cnt += count[i];
    16. if (cnt >= i) {
    17. return i;
    18. }
    19. }
    20. return 0;
    21. }
    22. }