My code:
public class Solution {
public int hIndex(int[] citations) {
int n = citations.length;
int begin = 0;
int end = n - 1;
while (begin <= end) {
int mid = begin + (end - begin) / 2;
if (citations[mid] > n - mid) {
end = mid - 1;
}
else if (citations[mid] < n - mid) {
begin = mid + 1;
}
else {
begin = mid;
break;
}
}
return n - begin;
}
}
用 Binary search 找最接近target并且 >= target 的 那个index
果然还是很常用的算法,一定要记住。
Anyway, Good luck, Richardo! -- 09/21/2016
网友评论