“This is my 36th day of participating in the First Challenge 2022. For details: First Challenge 2022”

The title

You are given an integer array of citations, where citations[I] represents the number of citations of the researcher’s i-th paper. Calculate and return the researcher’s H-index.

According to the Wikipedia h-index, where H stands for “high citations,” a researcher’s H-index means that h of his or her papers have been cited at least H times. Each of the other N-H papers was cited no more than H times.

If there are multiple possible values for h, the h exponent is the largest of them.

Example 1:

Input: citations = [3,0,6,1,5] Output: 3 Explanation: The given array means that the researcher has a total of 5 papers, and each paper has been cited 3,0,6,1,5 times accordingly. Since three of the researchers' papers were cited at least three times each, and the other two papers were cited no more than three times each, her H-index was 3.Copy the code

Example 2:

Citations = [1,3,1] Output: 1Copy the code

Tip:

n == citations.length
1 <= n <= 5000
0 <= citations[i] <= 1000
Copy the code

Source: LeetCode link: leetcode-cn.com/problems/h-… Copyright belongs to the Collar buckle network.

Their thinking

First sort paper citations, then scan from right to left by pointer: The pointer scans left from the first position on the right, and h increases successively from 1. When the paper reference of the h-position on the right (n-h, n is the total number of papers, and the n-position on the right = n-H) is less than H, the scanning is stopped and h is returned.

Taking [3,0,6,1,5] as an example, there are 5 papers in total, ranked as [0,1,3,5,6]

  • The first digit on the right is 6,6 >= 1, satisfying the condition;
  • The second digit on the right is 5,5 >= 2, satisfying the condition;
  • The third digit on the right is 3, 3 >= 3, satisfying the condition;
  • The fourth place on the right is 1, 1 < 4, which does not meet the condition (4 papers cited at least four times, the third paper is 3, and the fourth paper is 1, which does not meet the condition);
  • Return to 3;

Code implementation

var hIndex = function(citations) {
    // Sort papers by citations
    citations.sort((a, b) = > a - b)

    // Scan from the right to find the position that does not meet the condition
    let h = 1, n = citations.length
    
    // If n-h is greater than or equal to h, the condition is satisfied
    while(h <= n && citations[n - h] >= h) h++
    
    // The last time the condition is not satisfied, need to subtract
    return h - 1
};
Copy the code

If there are mistakes welcome to point out, welcome to discuss together!