Algorithm: Dichotomy---find H index

Insert image description here


1. Topic:

You are given an array of integers citations, where citations[i]represents the number of times the researcher's ipaper has been cited. Calculate and return the researcher's hindex .

According to the definition of h-index on Wikipedia: hit stands for "high citation count". A researcher's h index means that he or she has published at least hpapers, and each paper has been cited at leasth times. If hthere are multiple possible values, hthe 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’s ipaper 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

Insert image description here

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!

Guess you like

Origin blog.csdn.net/weixin_45630258/article/details/132894348