Question

Given an array of citations sorted in ascending order (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 than h citations each."

Note:

If there are several possible values for h, the maximum one is taken as the h-index.

Follow up:

  • This is a follow up problem to H-Index, where citations is now guaranteed to be sorted in ascending order.
  • Could you solve it in logarithmic time complexity?

Difficulty:Medium

Category:Array

Analyze

Solution

class Solution {
 public:
  int hIndex(vector<int>& citations) {
    int len_c = citations.size(), left = 0, right = len_c - 1;
    while (left <= right) {
      int mid_c = (right + left) / 2;
      if (citations[mid_c] == len_c - mid_c)
        return len_c - mid_c;
      else if (citations[mid_c] > len_c - mid_c) {
        right = mid_c - 1;
      } else {
        left = mid_c + 1;
      }
    }
    return len_c - left;
  }
};

Solution 2: Line Scan

class Solution {
 public:
  int hIndex(vector<int>& citations) {
    vector<int>& c = citations; 
    for (int i = 1; i <= c.size(); ++i) {
      if ( *(c.rbegin()+i-1) < i ) return i - 1;
    }
    return c.size();
  }
};
By guozetang            Updated: 2020-09-19 13:02:30

results matching ""

    No results matching ""