Better solution than Hint, no extra space

• Have a better solution without extra space.
Using in place divide (not sort) and the time in normal case is n + n/2 + n/4 + ... ~= 2n = O(n).
In worst case is: O(n^2), but just like quicksort, in most cases, it's a better solution.
It beats 100% submits at least in my desktop.

Here is the code:

``````public int hIndex(int[] citations)
{
int length = citations.length;
int start = 0;
int end = length - 1;
int hIndex = 0;

while (start <= end)
{
int current = divideByPartition(citations, start, end);
if (length - current <= citations[current])
{
hIndex = length - current;
end = current - 1;
}
else
start = current + 1;
}

return hIndex;
}

// divide the array by the last item and return the new index of this partition item.
private int divideByPartition(int[] a, int start, int end)
{
if (start == end) return end;

int p = a[end];
for (int current = start; current < end; current++)
{
if (a[current] < p)
{
a[current] = temp;
}
}
}``````

• This is called Quickselect. This is called Quickselect

• Well, no really. QuickSelect is to find the Kth item. In this question, you don't know the exact index in ahead. But if QuickSelect can make it easier to understand for you, I'm fine with it.

• The worse case complexity would be O(n^2) instead of O(n). Average complexity would be O(n) as you stated

• Yep, sorry for the confusion, but just like quicksort or quick select, in most case, it's a better solution. thanks

• The one used to find the Kth item is called "Randomized Selection"

• Still got confused why this will work..

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.