您的位置:首页 > 其它

leetcode-- H-Index I & II -- 重点常考

2015-12-22 11:11 288 查看

H-Index

https://leetcode.com/problems/h-index/

参考http://bookshadow.com/weblog/2015/09/03/leetcode-h-index/

思路1

用hash table 统计,key 为citation count,这里的key是设定好的[0,N], 即所有h value的可能值。 value为有多少篇paper有这些citation count。然后从后向前扫,直到sum[-i:] >= i就return.

class Solution(object):
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
N = len(citations)
cnts = [0] * (N + 1)
for c in citations:
cnts[[c, N][c > N]] += 1
sums = 0
for h in range(N, 0, -1):
if sums + cnts[h] >= h:
return h
sums += cnts[h]
return 0


思路2

线reverse排序,然后从左到右扫到index >= nums[i]就行

H-Index II

https://wenyuanjiao.gitbooks.io/algorithm_practice/content/h-index_ii.html

思路类似于H-index I中从右往左scan找到sum[-i:] >= i就return.

len - mid就是有多少paper的citations >= citations[mid]

琢磨一下bs的终止条件. 当i > j, 即input为[0,0]的时候

class Solution(object):
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
N = len(citations)
low, high = 0, N - 1
while low <= high:
mid = (low + high) / 2
if citations[mid] == N - mid:
return N - mid
elif N - mid > citations[mid]:
low = mid + 1
else:
high = mid - 1
return N - low
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: