We all know that large numbers to find the first k there is a very commonly used method is based fast lookup row, thinking fast row with essentially the same, as follows:
public int findKthLargest(int[] nums, int k) { return (findKthNum(nums,0,nums.length-1,k-1)); } private int findKthNum(int[] nums, int left, int right, int k){ int stan = nums[right]; int i = left, j = right; if (left == right && left == k) { return nums[left]; } else { while (i < j) { while (i < j && nums[i] >= stan) { i++; } while (i < j && nums[j] <= stan){ j--; } int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } } nums[right] = nums[i]; nums[i] = stan; if (k < i) { return findKthNum(nums, left, i - 1, k); } else if (k > i) { return findKthNum(nums, i + 1, right, k); } else { return nums[i]; } }
End split because each one side only proceed, the time complexity is O (n).
But just explained was a bit unclear, not by calculating hard to understand why it is O (n), for example, even if each operate only one side, then the number of traversal also log the n- times traversal is O ( n), is misleading for the method is O (nlog the n- ).
So here it is to return to the time complexity of specialized recurrence formula up.
We all know that quick sort of ideal, and the average time complexity is O (nlog the n- ), its recurrence formula is as follows, with merge sort basically the same, but with an average of ideal or limited because of the worst fast row is O (n ^ 2)
The average case: T (n-) = 2 * T (n-/ 2) + n-; first division = 2 * (2 * T ( n / 4) + n / 2) + n; a second division (= ^ 2 * T 2 (n-/. 4) + 2 * n-) = 2 * (2 * (2 * T (n-/. 8) n-+ /. 4) n-+ / 2) + n-; third division (= 2 . 3 * T * (n-/. 8). 3 * + n-) = ..................... = 2 ^ m + m * n-; m-th divided because 2 ^ = n-m, it is equivalent to m + n-* = n- so m = logN, so T (n) = n + n * logn;
Here it is quite easy to understand, then to find based on the time complexity of large numbers of fast k-row as follows:
The average case: T (n-) = T (n-/ 2) + n-; first division = T (n-/. 4) n-+ / 2 + n-; second division = T (n / 8) + n / n-+. 4/2 + n-; third division = ..................... = T (n-/ n-). 4 + + 2 + ... + n-; m-th division is a series of geometric summation formula, it is clear that T (n-) = 2N
Therefore, computation time complexity according to the recurrence formula is preferably stringent, this note based on the k-th row fast find large numbers, the average time complexity is also O (n).
"Introduction to Algorithms," Introduction to the next worst case is O (n) of the method, not described in detail herein, reference http://blog.chinaunix.net/uid-26456800-id-3407406.html