我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/h-index/
题目描述:
知识点:排序
思路一:排序后依次查找
时间复杂度是O(nlogn),其中n为数组的长度。空间复杂度是O(1)。
JAVA代码:
class Solution {
public int hIndex(int[] citations) {
Arrays.sort(citations);
for (int i = citations.length - 1; i >= 0; i--) {
if (citations[i] < citations.length - i) {
return citations.length - i - 1;
}
}
return citations.length;
}
}
LeetCode解题报告:
思路二:排序后二分查找
时间复杂度是O(nlogn),其中n为数组的长度。空间复杂度是O(1)。
JAVA代码:
class Solution {
public int hIndex(int[] citations) {
Arrays.sort(citations);
int left = 0, right = citations.length - 1, result = 0;
while (left <= right) {
int mid = left + (right - left) / 2;
if (citations[mid] == citations.length - mid) {
return citations.length - mid;
} else if (citations[mid] < citations.length - mid) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return citations.length - left;
}
}
LeetCode解题报告: