leetcode笔记:H-Index II

来源:互联网 发布:p站软件 编辑:程序博客网 时间:2024/06/05 14:19

一. 题目描述

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];    }};

四. 小结

题目的提示略显多余。

4 0