Leetcode: H-Index

來源:互聯網
上載者:User

標籤:

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:

  1. An easy approach is to sort the array first.
  2. What are the possible values of h-index?
  3. 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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.