[Leetcode] Binary search--275 H-Index

Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?

 Solution:

 # this is could also be solved used sorting or hash method reference as problem 274. H-index

here we use binary search
inspired from sorting method c[i] < i+1;
when citations c is in ascending order, the idea is find the minimum index c[i] >= len(c) -i

        l = 0
        h = len(citations)-1
        while (l <= h):
            mid = (l+h)/2
            if citations[mid] == len(citations)-mid:
               return len(citations)-mid
            elif citations[mid] < len(citations)-mid:
                l = mid+1
            else:
                h = mid-1
        
        return len(citations)-l
View Code

 

原文地址:https://www.cnblogs.com/anxin6699/p/6978068.html