标签:扫描 ret length pre 链接 堆排序 ems 一个 class
题目链接:https://leetcode-cn.com/problems/kth-largest-element-in-an-array/
1 先快速排序,再取第 K个
class Solution { public int findKthLargest(int[] nums, int k) { quickSort(nums,0,nums.length-1); return nums[nums.length-k]; } public void quickSort(int[] nums, int leftIndex, int rightIndex) { if (leftIndex > rightIndex) { return; } int left = leftIndex; int right = rightIndex; int key = nums[left]; while (left < right) { //从右往左扫描,找到第一个比基准值小的元素 while (left < right && nums[right] >= key) { right--; } //找到这种元素将arr[right]放入arr[left]中 nums[left] = nums[right]; while (left < right && nums[left] <= key) { //从左往右扫描,找到第一个比基准值大的元素 left++; } //找到这种元素将arr[left]放入arr[right]中 nums[right] = nums[left]; } //基准值归位 nums[left] = key; //对基准值左边的元素进行递归排序 quickSort(nums, leftIndex, left - 1); quickSort(nums, left + 1, rightIndex); } }
2 堆排序:
标签:扫描 ret length pre 链接 堆排序 ems 一个 class
原文地址:https://www.cnblogs.com/junbaba/p/14136118.html