视频分析:http://v.youku.com/v_show/id_XMTMzMzI5OTQ1Ng==.html
题干:
Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?
Hint:
Expected runtime complexity is in O(log n) and the input is sorted.
代码:
class Solution(object):
def match(self, citations, index):
num=len(citations)
return (True if citations[index]>=num-index else False)
def findFirstMatch(self, citations, start, end):
num=len(citations)
if(start==end):
if self.match(citations,start):
return num-start
else:
return 0
if(start+1==end):
if (not self.match(citations,start) and self.match(citations,end)):
return num-end
elif(self.match(citations,start) and self.match(citations,end)):
return num
else:
return 0
elif(self.match(citations,(start+end)//2)):
return self.findFirstMatch(citations,start,(start+end)//2)
else:
return self.findFirstMatch(citations,(start+end)//2,end)
def hIndex(self, citations):
num=len(citations)
if num<1:
return 0
return self.findFirstMatch(citations,0,num-1)