JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

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.”

Example:

Input: citations = [0,1,3,5,6]
Output: 3
Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had
             received 0, 1, 3, 5, 6 citations respectively.
             Since the researcher has 3 papers with at least 3 citations each and the remaining
             two with no more than 3 citations each, her h-index is 3.

Code

class Solution {
    public int hIndex(int[] citations) {
        if(citations == null || citations.length == 0){
            return 0;
        }

        int len = citations.length;
        
        int left = 0;
        int right = citations.length - 1;

        while(left + 1 < right){
            int mid = left + (right - left) / 2;
            if(citations[mid] == len - mid){
                return len - mid;
            } else if(citations[mid] > len - mid){
                right = mid;
            } else{
                left = mid;
            }
        }

        if(citations[left] >= len - left){
            return len - left;
        }

        if(citations[right] >= len - right){
            return len - right;
        }

        return 0;
    }
}
class Solution {
    public int hIndex(int[] citations) {
        if(citations == null || citations.length == 0) return 0;
        
        int count = 1;
        for(int i = citations.length - 1; i >= 0; i--){
            if(count <= citations[i]){
                count++;
            }
        }
        
        return count - 1;
        
    }
}
class Solution:
    def hIndex(self, citations: List[int]) -> int:
        if not citations:
            return 0

        start = 0
        end = len(citations) - 1

        while start + 1 < end:
            mid = (start + end) // 2

            if citations[mid] == len(citations) - mid:
                return len(citations) - mid
            elif citations[mid] > len(citations) - mid:
                end = mid
            else:
                start = mid

        if citations[start] >= len(citations) - start:
            return len(citations) - start

        if citations[end] >= len(citations) - end:
            return len(citations) - end

        return 0
class Solution:
    def hIndex(self, citations: List[int]) -> int:
        count = 1
        res = 0
        for i in range(len(citations) - 1, -1, -1):
            if count <= citations[i]:
                res = count

            count += 1

        return res