LeetCode 274 H指数,**基于比较的排序算法最优可以达到O(n*logn)的时间复杂度,算法导论中介绍了3种非基于比较的排序算法,时间复杂度可以达到线性。**LeetCode 274 是计数排序的典型应用,下面代码是中的注释比较详细,计数排序的思想并不复杂,如果忘记,请查看算法导论书籍。
class Solution {
public:
int hIndex(vector<int>& citations) {
vector<int> C(1001, 0);
int size = citations.size();
int ans = 0;
vector<int> out(size, 0);
//这里执行完C[i]是计数的功能
for(int d : citations) C[d]++;
//这里执行完C[i]表示小于i的数据个数
for(int i = 1; i < 1001; i++) C[i] += C[i - 1 ];
for(int i = size - 1; i >= 0; i--){
int index = C[citations[i]] - 1;
out[index] = citations[i];
//这一行的目的是当citations中的数据有重复时起作用,由于是
//从大到小遍历,这里决定了计数排序算法的稳定性
C[citations[i]]--;
/*
if(citations[i] >= size - index){
ans = size - index > ans ? size - index: ans;
}
*/
}
//这个for循环可以使用上面注释掉的if代替
for(int i = size - 1; i >= 0; i--){
if(out[i] >= size - i){
ans = size - i > ans ? size - i : ans;
}
}
return ans;
}
};