Follow up for H-Index: What if the
citations
array is sorted in ascending order? Could you optimize your algorithm?
Hint:
- Expected runtime complexity is in O(log n) and the input is sorted.
Solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
}; |
No comments:
Post a Comment