
LeetCode 274. H-Index
Description
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 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, her h-index is 3.
Note: If there are several possible values for h, the maximum one is taken as the h-index.
描述
給定一位研究者論文被引用次數(shù)的數(shù)組(被引用次數(shù)是非負(fù)整數(shù))。編寫(xiě)一個(gè)方法,計(jì)算出研究者的 h 指數(shù)。
h 指數(shù)的定義: “h 代表“高引用次數(shù)”(high citations),一名科研人員的 h 指數(shù)是指他(她)的 (N 篇論文中)至多有 h 篇論文分別被引用了至少 h 次。(其余的 N - h 篇論文每篇被引用次數(shù)不多于 h 次。)”
示例:
輸入: citations = [3,0,6,1,5]
輸出: 3
解釋: 給定數(shù)組表示研究者總共有 5 篇論文,每篇論文相應(yīng)的被引用了 3, 0, 6, 1, 5 次。
由于研究者有 3 篇論文每篇至少被引用了 3 次,其余兩篇論文每篇被引用不多于 3 次,所以她的 h 指數(shù)是 3。
說(shuō)明: 如果 h 有多種可能的值,h 指數(shù)是其中最大的那個(gè)。
思路
- 對(duì)數(shù)組進(jìn)行排序,然后從后往前遍歷.
- h表示至少有h個(gè)元素在h之上,h初始化為0,從后往前走的過(guò)程中,沒(méi)向前走一步,h自增一次,當(dāng)當(dāng)前元素小于h時(shí),我們返回h.
# -*- coding: utf-8 -*-
# @Author: 何睿
# @Create Date: 2019-02-05 12:24:54
# @Last Modified by: 何睿
# @Last Modified time: 2019-02-05 19:45:16
class Solution:
def hIndex(self, citations: 'List[int]') -> 'int':
# 如果輸入為空,返回0
if not citations: return 0
h = 0
# 對(duì)輸入的數(shù)據(jù)排序
citations.sort()
# 從后向前遍歷
for item in citations[-1::-1]:
# 根據(jù)題意,至少有h個(gè)元素大于h
h += 1
# 如果出現(xiàn)當(dāng)前元素小于h時(shí),說(shuō)明已經(jīng)不滿足給定的條件,函數(shù)返回
if item < h:
h -= 1
break
return h
源代碼文件在這里.
?本文首發(fā)于何睿的博客,歡迎轉(zhuǎn)載,轉(zhuǎn)載需保留文章來(lái)源,作者信息和本聲明.