image.png

解题思路

image.png

  1. class Solution {
  2. public int findKthLargest(int[] nums, int k) {
  3. // init heap 'the smallest element first'
  4. PriorityQueue<Integer> heap =
  5. new PriorityQueue<Integer>((n1, n2) -> n1 - n2);
  6. // keep k largest elements in the heap
  7. for (int n: nums) {
  8. heap.add(n);
  9. if (heap.size() > k)
  10. heap.poll();
  11. }
  12. // output
  13. return heap.poll();
  14. }
  15. }
  • 时间复杂度 : {O}(N log k)。
  • 空间复杂度 : {O}(k),用于存储堆元素。

    快速排序

    image.png
  1. import java.util.Random;
  2. class Solution {
  3. int [] nums;
  4. public void swap(int a, int b) {
  5. int tmp = this.nums[a];
  6. this.nums[a] = this.nums[b];
  7. this.nums[b] = tmp;
  8. }
  9. public int partition(int left, int right, int pivot_index) {
  10. int pivot = this.nums[pivot_index];
  11. // 1. move pivot to end
  12. swap(pivot_index, right);
  13. int store_index = left;
  14. // 2. move all smaller elements to the left
  15. for (int i = left; i <= right; i++) {
  16. if (this.nums[i] < pivot) {
  17. swap(store_index, i);
  18. store_index++;
  19. }
  20. }
  21. // 3. move pivot to its final place
  22. swap(store_index, right);
  23. return store_index;
  24. }
  25. public int quickselect(int left, int right, int k_smallest) {
  26. /*
  27. Returns the k-th smallest element of list within left..right.
  28. */
  29. if (left == right) // If the list contains only one element,
  30. return this.nums[left]; // return that element
  31. // select a random pivot_index
  32. Random random_num = new Random();
  33. int pivot_index = left + random_num.nextInt(right - left);
  34. pivot_index = partition(left, right, pivot_index);
  35. // the pivot is on (N - k)th smallest position
  36. if (k_smallest == pivot_index)
  37. return this.nums[k_smallest];
  38. // go left side
  39. else if (k_smallest < pivot_index)
  40. return quickselect(left, pivot_index - 1, k_smallest);
  41. // go right side
  42. return quickselect(pivot_index + 1, right, k_smallest);
  43. }
  44. public int findKthLargest(int[] nums, int k) {
  45. this.nums = nums;
  46. int size = nums.length;
  47. // kth largest is (N - k)th smallest
  48. return quickselect(0, size - 1, size - k);
  49. }
  50. }
  • 时间复杂度 : 平均情况 {O}(N,最坏情况O(_N_2)。
  • 空间复杂度 : {O}(1。