思路
- 这道题可以用一个大小为k的小根堆来做,这样时间复杂度为O(nlogk)
- 但是也可以用快速排序~ 一定要注意partition函数的写法哦
public class Solution { private void swap(int[] nums, int left, int right) { int tmp = nums[left]; nums[left] = nums[right]; nums[right] = tmp; } private int partition(int[] nums, int left, int right) { if (left < right) { int random = new Random().nextInt(right - left + 1) + left; swap(nums, random, right); int pre = left - 1, cur = left; while (cur <= right) { if (nums[cur] <= nums[right]) { pre++; swap(nums, pre, cur); } cur++; } return pre; } return left; } public int findKthLargest(int[] nums, int k) { int left = 0, right = nums.length - 1, index = partition(nums, 0, nums.length - 1); while (index != nums.length - k) { if (index < nums.length - k) left = index + 1; else right = index - 1; index = partition(nums, left, right); } return nums[index]; } }