Friday, April 22, 2016

LeetCode Q275: H-Index II

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 in O(log n) and the input is sorted.
Solution:

class Solution {
public:
void helper(vector<int>& citations, int left, int right, int& h){
if(left>right)
return;
int m=(left+right)/2;
int n=citations.size();
if(n-m == citations[m]){
h=citations[m];
return;
}
h = max(h, min(citations[m], n-m));
if(n-m>citations[m])
helper(citations, m+1, right, h);
if(n-m<citations[m])
helper(citations, left, m-1, h);
}
int hIndex(vector<int>& citations) {
int h=0;
helper(citations, 0, citations.size()-1, h);
return h;
}
};
view raw Q275.cpp hosted with ❤ by GitHub

No comments:

Post a Comment