算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 H 指数 II,我们先来看题面:
https://leetcode-cn.com/problems/h-index-ii/
Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper and citations is sorted in an ascending order, return compute the researcher's h-index.
According to the definition of h-index on Wikipedia: A scientist has an index h if h of their n papers have at least h citations each, and the other n − h papers have no more than h citations each.
If there are several possible values for h, the maximum one is taken as the h-index.
You must write an algorithm that runs in logarithmic time.
给定一位研究者论文被引用次数的数组(被引用次数是非负整数),数组已经按照 升序排列 。编写一个方法,计算出研究者的 h 指数。
h 指数的定义: “h 代表“高引用次数”(high citations),一名科研人员的 h 指数是指他(她)的 (N 篇论文中)总共有 h 篇论文分别被引用了至少 h 次。(其余的 N - h 篇论文每篇被引用次数不多于 h 次。)"
示例
输入: citations = [0,1,3,5,6]
输出: 3
解释: 给定数组表示研究者总共有 5 篇论文,每篇论文相应的被引用了 0, 1, 3, 5, 6 次。
由于研究者有 3 篇论文每篇至少被引用了 3 次,其余两篇论文每篇被引用不多于 3 次,所以她的 h 指数是 3。
解题
https://blog.csdn.net/qq_41855420/article/details/88210221
此题给的条件是递增的数组序列,所以我们需要充分利用。
方法一:从后往前遍历数组,如果出现引用大于等于hRes次的论文数量大于、等于hRes时,hRes就是结果。(时间复杂度O(n),额外的空间复杂度O(1))
class Solution {
public:
int hIndex(vector<int>& citations) {
int citationsSize = citations.size();
int cnt = 0, hRes = citationsSize;//cnt表示引用次数大于、等于hRes论文数,hRes代表的是当前的标准,初始化为最大值
//注意循环条件index >= 0表示不出界,cnt < hRes表示引用次数大于等于hRes的论文数cnt小于hRes
for (int index = citationsSize - 1; cnt < hRes && index >= 0; ) {
if (hRes <= citations[index]) {//citations[index]表示的当前论文引用的次数超过了标准
cnt += 1;
index -= 1;
}
else {//否则需要降低标准
hRes -= 1;
}
}
return hRes;
}
};
方法二:提到log(n)的时间复杂度,那么与二分法一般都分不开。
class Solution {
public:
int hIndex(vector<int>& citations) {
int citationsSize = citations.size();
if (citationsSize == 0){
return 0;
}
//二分法的左、中、右指针
int left = 0, mid, right = citationsSize - 1;
while (left < right) {
mid = (left + right) / 2;
//因为数组递增,所以mid下标之后的论文引用次数必定 >= citations[mid]
//citationsSize - mid代表是从下标mid到末端[mid, citationsSize - 1]含有的论文数
//citations[mid] >= citationsSize - mid进行判断mid是否符合标准
//因为需要找到H的最大值,所以citationsSize - mid需要尽可能的大
if (citations[mid] >= citationsSize - mid) {
right = mid;
}
else {
left = mid + 1;
}
}
//防止所有的所有的论文引用都是0的情况,如果不加特殊处理,将会返回1
if (citations[right] < citationsSize - right) {
return 0;
}
return citationsSize - right;
}
};
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文: