[Leetcode]H-Index II

来源:互联网 发布:微信用户分析数据接口 编辑:程序博客网 时间:2024/05/19 13:24

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

Hint:

  1. Expected runtime complexity is inO(log n) and the input is sorted.


class Solution {public:    /*algorithm: binary search        time O(nlogn) space O(1)    */    int hIndex(vector<int>& citations) {        int n = citations.size();        int l = 0,r = n-1;        while(l <= r){            int h = l + (r-l)/2;            if(citations[h] == n-h)return n-h;            else if(citations[h] > n-h)r = h-1;            else l = h+1;        }        return n-l;    }};


0 0