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

来源:互联网 发布:央视市场研究 知乎 编辑:程序博客网 时间:2024/06/06 19:08

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
原创粉丝点击