Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more thanh citations each."
For example, given citations = [3, 0, 6, 1, 5]
, which means the researcher has 5
papers in total and each of them had received 3, 0, 6, 1, 5
citations respectively. Since the researcher has 3
papers with at least 3
citations each and the remaining two with no more than 3
citations each, his h-index is 3
.
Note: If there are several possible values for h
, the maximum one is taken as the h-index.
题意:给出一个数组,求这样的一个数h,数组中的h个数的值大于等于h,如果有多个,取最大的。
思路:从大到小排序,判断当前元素组是否大于其下标,如果是,继续判断,直到当前元素值小于或等于下标
代码如下:
class Solution
{
public int hIndex(int[] citations)
{
Comparator cmp = new Comparator() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
};
Integer[] tmp = new Integer[citations.length];
for (int i = 0; i < tmp.length; i++)
{
tmp[i] = new Integer(citations[i]);
}
Arrays.sort(tmp, cmp);
int i = 0;
for (i = 0; i < citations.length; i++)
{
citations[i] = tmp[i].intValue();
if (citations[i] <= i)
{
break;
}
}
return i;
}
}
方法二:用计数来达到排序,如果元素值大于数组长度,就将对应的count[len]加1,然后从尾到 头计算大于当前下标的数目,如果和大于当前下标,说明当前下标就是所求的值 。
代码如下:
class Solution
{
public int hIndex(int[] citations)
{
int n = citations.length;
int[] count = new int[n + 1];
for (int i = 0; i < n; i++)
{
if (citations[i] >= n) count[n]++;
else count[citations[i]]++;
}
int ans = 0;
for (int i = n; i >= 0; i--)
{
ans += count[i];
if (ans >= i) return i;
}
return ans;
}
}