本题我用sort的方法解出来了,但是这种方法的时间复杂度是,所以明显不是最好的,参考了答案,答案用的是一个近似HashMap或者说是bucket sort的方法
- 定义一个array,
arr[i]
表示citations
里面等于i
的数量(最后一个除外) 从后向前遍历,当
cnt >= i
的是时候,代表有且之后i个元素的值大于等于i
,继续遍历的话,只会得到更小的i
时间复杂度:
- 空间复杂度:
代码如下:
class Solution {
public int hIndex(int[] citations) {
int n = citations.length;
int[] count = new int[n+1];
for (int citation : citations) {
if (citation > citations.length) {
count[n] += 1;
}
else {
count[citation] += 1;
}
}
int cnt = 0;
for (int i = n; i >= 0; --i) {
cnt += count[i];
if (cnt >= i) {
return i;
}
}
return 0;
}
}