关闭

leetcode :Binary Search: H-Index IIe(275)

51人阅读 评论(0) 收藏 举报
分类:

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

Expected runtime complexity is in O(log n) and the input is sorted.


class Solution {
public:
    // binary search - O(log(n))
    int hIndex(vector<int>& citations) {
        int n = citations.size();
        int low = 0, high = n-1;

        while( low <= high ) {
            int mid = low + (high-low)/2;
            if (citations[mid] == n - mid) {
                return n - mid;
            }else if (citations[mid] > n-mid){
                high = mid - 1;
            }else {
                low = mid + 1;
            }
        }
        return n-low;
    }
};
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:115524次
    • 积分:6816
    • 等级:
    • 排名:第3538名
    • 原创:589篇
    • 转载:2篇
    • 译文:0篇
    • 评论:2条
    最新评论