forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
h-Index.II.cpp
33 lines (28 loc) · 935 Bytes
/
h-Index.II.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Source : https://leetcode.com/problems/h-index-ii/
// Author : Hao Chen
// Date : 2015-11-08
/***************************************************************************************
*
* Follow up for H-Index: What if the citations array is sorted in ascending order?
* Could you optimize your algorithm?
*
***************************************************************************************/
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;
}
};