image.png
    解析:方法1:优先级队列, 方法2:快速排序

    1. class Solution {
    2. public int findKthLargest(int[] nums, int k) {
    3. //方法1:优先级队列(堆排序)
    4. PriorityQueue<Integer> queue = new PriorityQueue<>((o1, o2) -> o2 - o1);
    5. for (int num : nums) {
    6. queue.add(num);
    7. }
    8. for (int i = 0; i < k - 1; i++) {
    9. queue.remove();
    10. }
    11. return queue.remove();
    12. }
    13. }
    1. class Solution {
    2. public int findKthLargest(int[] nums, int k) {
    3. //方法2:快速排序(随机找基准,当基准正好落在k-1的位置上时,该基准就是所求)
    4. while (true) {
    5. int[] index = partition(nums, 0, nums.length - 1);
    6. if (index[0] <= nums.length - k && nums.length - k <= index[1]) {
    7. return nums[index[0]];
    8. }
    9. }
    10. }
    11. private int[] partition(int[] arr, int start, int end) {
    12. int target = arr[new Random().nextInt(end+1)]; //指定一个数,将数组变成
    13. //<target =target >target 三部分
    14. int less = -1, more = end + 1, p = 0;
    15. while (p < more) {
    16. if (arr[p] > target) {
    17. swap(arr, p, --more);
    18. } else if (arr[p] < target) {
    19. swap(arr, ++less, p++);
    20. } else {
    21. p++;
    22. }
    23. }
    24. return new int[]{less + 1, more - 1};
    25. }
    26. private void swap(int[] arr, int i, int j) {
    27. int tmp = arr[i];
    28. arr[i] = arr[j];
    29. arr[j] = tmp;
    30. }
    31. }