1. Topic:
You are given an array of integers citations
, where citations[i]
represents the number of times the researcher's i
paper has been cited. Calculate and return the researcher's h
index .
According to the definition of h-index on Wikipedia: h
it stands for "high citation count". A researcher's h
index means that he or she has published at least h
papers, and each paper has been cited at leasth
times. If h
there are multiple possible values, h
the exponent is the largest of them.
2. Analysis features:
- Question requirement: Find the maximum value,
citations[i]
which represents the number of times the researcher’si
paper has been cited ==> After sorting, use the dichotomy method. - Common scenarios for using the binary method ==> Searching ordered lists: When you need to find a specific element in an ordered list (such as an array), you can use the binary method.
3. Code:
class Solution {
public int hIndex(int[] citations) {
int left=0,right=citations.length;
int mid=0,cnt=0;
while(left<right){
// +1 防止死循环
mid=(left+right+1)>>1;
cnt=0;
for(int i=0;i<citations.length;i++){
if(citations[i]>=mid){
cnt++;
}
}
if(cnt>=mid){
// 要找的答案在 [mid,right] 区间内
left=mid;
}else{
// 要找的答案在 [0,mid) 区间内
right=mid-1;
}
}
return left;
}
}
4. Complexity analysis:
- Time complexity: O(nlogn), where n is the length of the citations array. Logn binary searches are required, and each binary search requires traversing the citations array once.
Space complexity: O(1), only constant variables are needed for binary search.
5. Summary:
Common scenarios for using the binary method ==> Searching ordered lists: When you need to find a specific element in an ordered list (such as an array), you can use the binary method.
6. Other solutions: sorting method
Problem-solving idea: After ascending order, just determine whether the current number is greater than its corresponding h value.
■ Code:
import java.util.Arrays;
class Solution {
public int hIndex(int[] citations) {
Arrays.sort(citations);
int length = citations.length;
for (int i = 0; i < length; i++) {
if (citations[i] >= length - i) {
return length - i;
}
}
return 0;
}
}
If this article is helpful to you, please remember to give Yile a like, thank you!