275. H-Index II

时间:2023-12-04 16:20:56

题目:

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

Hint:

  1. Expected runtime complexity is in O(log n) and the input is sorted.

链接: http://leetcode.com/problems/h-index-ii/

题解:

假如给定数组是排序好的,求H-Index。 我们就可以用Binary Search。 target = len - mid。

Time Complexity - O(logn), Space Complexity - O(1)

public class Solution {
public int hIndex(int[] citations) {
if(citations == null || citations.length == 0) {
return 0;
}
int len = citations.length, lo = 0, hi = len - 1; while(lo <= hi) {
int mid = lo + (hi - lo) / 2;
if(citations[mid] == len - mid) {
return citations[mid];
} else if(citations[mid] > (len - mid)) {
hi = mid - 1;
} else {
lo = mid + 1;
}
} return len - lo;
}
}

题外话: 房子的装修师傅今天离开了,但是关键的电炉灶没接好,原因是总闸处220v电线有问题,导致插座没电。不过都是熟人,我也不想他们碰处一些危险的东西。虽然还要另找电工检查线路和接线,很费事费钱,但我想明年争取换份好工作,挣回来就好了。

二刷:

对于在位置i的论文来说, 至少len - i的论文, citations数目都比位置i的论文大。所以i位置的h-index至少是len - i。我们就可以用Binary Search来搜索答案。

Java:

public class Solution {
public int hIndex(int[] citations) {
if (citations == null || citations.length == 0) {
return 0;
}
int len = citations.length, lo = 0, hi = len - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (citations[mid] == len - mid) {
return citations[mid];
} else if (citations[mid] < len - mid) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return len - lo;
}
}

Reference:

https://leetcode.com/discuss/56122/standard-binary-search

https://leetcode.com/discuss/56170/java-binary-search-simple-and-clean