標籤:
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."For example, given citations = [3, 0, 6, 1, 5], which means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 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, his h-index is 3.Note: If there are several possible values for h, the maximum one is taken as the h-index.
Hint:
- An easy approach is to sort the array first.
- What are the possible values of h-index?
- A faster approach is to use extra space.
Sort first then scan: O(NlogN) time, O(1)space
use another array: O(N) time, O(N) space
我們額外使用一個大小為N+1的數組stats。stats[i]表示有多少文章被引用了i次,這裡如果一篇文章引用大於N次,我們就將其當為N次,因為H指數不會超過文章的總數。為了構建這個數組,我們需要先將整個文獻引用數組遍曆一遍,對相應的格子加一。統計完後,我們從N向1開始遍曆這個統計數組。如果遍曆到某一個引用次數時,大於或等於該引用次數的文章數量,大於引用次數本身時,我們可以認為這是H指數。之所以不用再向下找,因為我們要取最大的H指數。那如何求大於或等於某個引用次數的文章數量呢?我們可以用一個變數,從高引用次的文章數累加下來。因為我們知道,如果有x篇文章的引用大於等於3次,那引用大於等於2次的文章數量一定是x加上引用次數等於2次的文章數量。
1 public class Solution { 2 public int hIndex(int[] citations) { 3 int N = citations.length; 4 int[] summary = new int[N+1]; 5 for (int m : citations) { 6 if (m <= N) summary[m]++; 7 else summary[N]++; 8 } 9 int sum = 0;10 for (int j=summary.length-1; j>=0; j--) {11 sum += summary[j]; //sum means # of papers that has citation greater than or equal to j12 if (sum >= j) return j;13 }14 return 0;15 }16 }
Leetcode: H-Index