leetcode笔记:H-Index II

一. 题目描述

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

二. 题目分析

该题与H-Index一题的要求基本一致,只是多提供了一个条件,即传入的数组本身已经是升序排列的,因此实际上操作会方便许多,也无需再使用辅助数组。该题仍然可以使用H-Index方法从后往前遍历数组,即可计算出h指数,算法复杂度为O(n),但更快的方法是使用二分查找,复杂度降为O(logn)

三. 示例代码

// 简单的从后往前遍历数组,较为耗时
class Solution {
public:
    int hIndex(vector<int>& citations) {
        if (citations.size() == 0) return 0;
        int result = 0;
        for (int i = citations.size() - 1; i >= 0; --i)
        {
            if (result >= citations[i])
                return result;
            ++result;
        }
        return citations.size();
    }
};
// 二分查找,效率更快
class Solution {
public:
    int hIndex(vector<int>& citations) {
        int size = citations.size();
        if (size == 0)
            return 0;
        int left = 0, right = size - 1;
        while (left < right){
            int mid = left + (right - left) / 2;
            if (size - mid > citations[mid])
                left = mid + 1;
            else
                right = mid;
        }
        return (size - right) < citations[right] ? (size - right) : citations[right];
    }
};

四. 小结

题目的提示略显多余。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值