Follow up for H-Index:
What if the citations
array
is sorted in ascending order? Could you optimize your algorithm?
基本思路:折半查找
1. 選取中間點,判斷該處是否滿足hIndex定義
2. 如果滿足定義,則在左區間繼續搜索,以找到更大的hIndex
3. 如果不滿足定義,在則在右區間搜索,以找到滿足定義的點。
4. 重複步驟1.2.3,直到區間爲空。
關於返回值設爲 M - stop -1的正確性:
在縮小區間過程中,總是維持一不變式: stop後面的元素總是滿足hIndex定義。
包括其初始值。即citations末尾之後的元素,也滿足hIndex定義,其值爲0。
class Solution {
public:
int hIndex(vector<int>& citations) {
const int M = citations.size();
int start = 0, stop = M - 1;
int hIndex = 0;
while (start <= stop) {
const int mid = start + (stop - start >> 1);
if (citations[mid] >= M - mid)
stop = mid - 1;
else
start = mid + 1;
}
return M - stop - 1;
}
};