您的位置:首页 > 其它

【Leetcode】H-Index II

2016-06-03 22:25 330 查看
题目链接:https://leetcode.com/problems/h-index-ii/

题目:

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.

思路:

用二分查找法。

算法:

[java] view
plain copy

 





public int hIndex(int[] citations) {  

    int h = 0;  

    int right = citations.length - 1, left = 0, mid = (right - left) / 2 + left;  

    while (right >= left) {  

        if (citations[mid] < citations.length - mid) {  

            left = mid + 1;  

        } else if (citations[mid] >= citations.length - mid) {  

            right = mid - 1;  

            h = citations.length - mid;  

            if (mid - 1 >= 0 && citations[mid - 1] < citations.length - mid + 1)  

                return h;  

        }  

        mid = (right - left) / 2 + left;  

    }  

    return h;  

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: