LeetCode 274. H-Index
原题链接在这里:https://leetcode.com/problems/h-index/
题目:
Given an array of citations (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 = [3,0,6,1,5]
Output: 3 Explanation:[3,0,6,1,5]
means the researcher has5
papers in total and each of them had received3, 0, 6, 1, 5
citations respectively. Since the researcher has3
papers with at least3
citations each and the remaining two with no more than3
citations each, her h-index is3
.
Note: If there are several possible values for h, the maximum one is taken as the h-index.
题解:
两种方法,第一种方法是sorting, after sorting, could guess and use binary search.
Time Complexity O(nlogn). Space O(1).
AC Java:
1 class Solution { 2 public int hIndex(int[] citations) { 3 if(citations == null || citations.length == 0){ 4 return 0; 5 } 6 7 Arrays.sort(citations); 8 int n = citations.length; 9 int l = 0; 10 int r = n - 1; 11 while(l <= r){ 12 int mid = l + (r - l) / 2; 13 if(citations[mid] == n - mid){ 14 return citations[mid]; 15 }else if(citations[mid] < n - mid){ 16 l = mid + 1; 17 }else{ 18 r = mid - 1; 19 } 20 } 21 22 return n - l; 23 } 24 }
第二种方法是用空间换时间. count[i] 存储 被引用了i遍的文章有几个,最后total的含义就是总共有几篇文章引用次数大于等于i. 引用次数大于等于 len的都算在 count[len]里面.
Time Complexity is O(n), Space O(n).
AC Java:
1 public class Solution { 2 public int hIndex(int[] citations) { 3 /* 4 //Method 1 5 if(citations == null || citations.length == 0){ 6 return 0; 7 } 8 Arrays.sort(citations); 9 int res = 0; 10 for(int i = citations.length-1; i>=0; i--){ 11 if(citations[i] >= citations.length-i){ 12 res = citations.length-i; 13 } 14 } 15 return res; 16 */ 17 18 //Method 2 19 if(citations == null || citations.length == 0){ 20 return 0; 21 } 22 int len = citations.length; 23 //count 数组储存了被引用 i 遍的文章有几个,i是count的index 24 int [] count = new int[len+1]; 25 for(int i = citations.length - 1; i>=0; i--){ 26 if(citations[i]>=citations.length){ 27 count[len]++; 28 }else{ 29 count[citations[i]]++; 30 } 31 } 32 //total 计数总共有几篇文章引用大于等于i次,i是count 的index 33 int total = 0; 34 for(int i = len; i>=0; i--){ 35 total += count[i]; 36 if(total>=i){ //有三篇文章引用大于等于三次 37 return i; 38 } 39 } 40 return 0; 41 } 42 }
跟上H-Index II.