先排序
// 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}
时的计数情况: