好吧,原来辛苦打的被csdn吃了,跟以往一样,被吃掉的文章我就只暂时放出简要的描述和代码
解法一:基于排序的O(nlogn),就是先排序,然后找到第一个citations[i],它比citations.length - i要大(也就是剩下的论文)。给出代码如下:
public int hIndex(int[] citations) {
Arrays.sort(citations);
for (int i = 0; i < citations.length; i++) {
int citationsLeft = citations.length - i;
if (citations[i] >= citationsLeft) return citationsLeft;
}
return 0;
}
解法二: 基于selection rank的最坏O(n^2),平均O(n),就是不停通过partition找,找到最小的citations[mid], 它大于等于citations.length - mid,其实和排序的最终完结条件是一样的,但我们并没有做完全的排序。
public int hIndex(int[] citations) {
int head = 0, tail = citations.length - 1, maxCandidate = 0;
while (head <= tail) {
int mid = partition(head, tail, citations);
int candidate = citations.length - mid;
if (citations[mid] == candidate) {
return candidate;
} else if (citations[mid] > candidate) {
maxCandidate = Math.max(candidate, maxCandidate);
tail = mid - 1;
} else {
head = mid + 1;
}
}
return maxCandidate;
}
public void swap(int[] arr, int a, int b) {
if (a != b) {
arr[a] ^= arr[b];
arr[b] ^= arr[a];
arr[a] ^= arr[b];
}
}
public int partition(int head, int tail, int[] arr) {
Random rand = new Random();
int pivotIndx = head + rand.nextInt(tail - head + 1);
swap(arr, pivotIndx, tail);
int pivot = arr[tail];
int j = head;
for (int i = head; i < tail; i++) {
if (pivot >= arr[i]) {
swap(arr, i, j);
j++;
}
}
swap(arr, tail, j);
return j;
}