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

思路

接上一题,按顺序排列,方法更为简洁。一趟遍历即可解决。

P.S. 更可以用二分查找法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int hIndex(vector<int>& citations) {
int result = 0;
if(citations.size()>0){
for (int i = citations.size() - 1; i >= 0; i--){
int count = citations.size() - i;
if(citations[i] >= count) {
result = max(count, result);
}
}
if(result > 0) return result;
else{
int size = citations.size();
int start = citations[0];
result = min(size, start);
return result;
}
}
else return 0;
}
};