【LeetCode】275. H-Index II 二叉樹的所有路徑(Medium)(JAVA)
技術標籤:Leetcode演算法leetcodejava資料結構面試
【LeetCode】275. H-Index II 二叉樹的所有路徑(Medium)(JAVA)
題目地址: https://leetcode.com/problems/h-index-ii/
題目描述:
Given an array of citations sortedin ascending order (each citation is a non-negative integer) of a researcher, write a function to compute the researcher’s h-index.
According to thedefinition of h-index on Wikipedia: “A scientist has indexhifhof his/herNpapers haveat leasthcitations each, and the otherN − hpapers haveno more thanhcitations each.”
Example:
Input: citations = [0,1,3,5,6]
Output: 3
Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had
Since the researcher has 3 papers with at least 3 citations each and the remaining
two with no more than 3 citations each, her h-index is 3.
Note:
If there are several possible values forh, the maximum one is taken as the h-index.
Follow up:
- This is a follow up problem toH-Index, where citations is now guaranteed to be sorted in ascending order.
- Could you solve it in logarithmic time complexity?
題目大意
給定一位研究者論文被引用次數的陣列(被引用次數是非負整數),陣列已經按照升序排列。編寫一個方法,計算出研究者的 h 指數。
h 指數的定義: “h 代表“高引用次數”(high citations),一名科研人員的 h 指數是指他(她)的 (N 篇論文中)總共有 h 篇論文分別被引用了至少 h 次。(其餘的N - h篇論文每篇被引用次數不多於 h 次。)"
說明:
如果 h 有多有種可能的值 ,h 指數是其中最大的那個。
進階:
- 這是H 指數的延伸題目,本題中的citations陣列是保證有序的。
- 你可以優化你的演算法到對數時間複雜度嗎?
解題方法
- 因為 citations 已經排好序了,也知道了判斷是否是 h 的條件 citations[citations.length - h] >= h
- 採用二分法判斷最大的 h 即可(主要是把 == 的情況放在了 start 這邊就行)
class Solution {
public int hIndex(int[] citations) {
if (citations.length <= 0 || citations[citations.length - 1] == 0) return 0;
int start = 1;
int end = citations.length;
while (start <= end) {
int mid = start + (end - start) / 2;
if (citations[citations.length - mid] >= mid) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return end;
}
}
執行耗時:0 ms,擊敗了100.00% 的Java使用者
記憶體消耗:45.2 MB,擊敗了86.16% 的Java使用者