题目:
Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?
思路:
做这道题目的时候,我才发现上一道题目其实排序后可以利用二分查找将时间复杂度降为O(logn)。和普通二分取中不同的是,我们关注的大于citations[mid]的文章数和citations[mid]的关系,根据这个关系不断缩小搜索范围。
代码:
class Solution {
public:
int hIndex(vector<int>& citations) {
int size = citations.size(), left = 0, right = size - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
int count = size - mid;
if (citations[mid] < count) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
return size - left;
}
};
本文介绍了一种针对已排序引用数组的H-Index算法优化方案,通过二分查找技术将时间复杂度降低到O(log n),并详细解释了实现思路及代码细节。
383

被折叠的 条评论
为什么被折叠?



