215. 数组中的第K个最大元素

  1. class Solution {
  2. public int findKthLargest(int[] nums, int k) {
  3. int heapSize = nums.length;
  4. buildMaxHeap(nums, heapSize);
  5. for (int i = nums.length - 1; i >= nums.length - k + 1; --i) {
  6. swap(nums, 0, i);
  7. --heapSize;
  8. maxHeapify(nums, 0, heapSize);
  9. }
  10. return nums[0];
  11. }
  12. public void buildMaxHeap(int[] a, int heapSize) {
  13. for (int i = heapSize / 2; i >= 0; --i) {
  14. maxHeapify(a, i, heapSize);
  15. }
  16. }
  17. public void maxHeapify(int[] a, int i, int heapSize) {
  18. int l = i * 2 + 1, r = i * 2 + 2, largest = i;
  19. if (l < heapSize && a[l] > a[largest]) {
  20. largest = l;
  21. }
  22. if (r < heapSize && a[r] > a[largest]) {
  23. largest = r;
  24. }
  25. if (largest != i) {
  26. swap(a, i, largest);
  27. maxHeapify(a, largest, heapSize);
  28. }
  29. }
  30. public void swap(int[] a, int i, int j) {
  31. int temp = a[i];
  32. a[i] = a[j];
  33. a[j] = temp;
  34. }
  35. }
  36. 作者:LeetCode-Solution
  37. 链接:https://leetcode-cn.com/problems/kth-largest-element-in-an-array/solution/shu-zu-zhong-de-di-kge-zui-da-yuan-su-by-leetcode-/