LeetCode-215、Kth Largest Element in an Arrayhttps://leetcode.com/problems/kth-largest-element-in-an-array/
题目描述Given an integer array nums and an integer k, return the kth largest element in the array.
Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: nums = [3,2,1,5,6,4], k = 2Output: 5
Example 2:
Input: nums = [3,2,3,1,2,4,5,5,6], k = 4Output: 4
Constraints:
1 <= k <= nums.length <= 104-104 <= nums[i] <= 104 解题思路
【C++】
快排partition
1、循环class Solution {public: int findKthLargest(vector
class Solution {public: int findKthLargest(vector
class Solution { public int findKthLargest(int[] nums, int k) { if (nums.length == 0 || nums.length < k) { return -1;} partition(nums, 0, nums.length - 1, --k); return nums[k]; } void partition(int[] nums, int low, int high, int k) { int pivot = nums[low], l = low, h = high; while(l < h) { while(pivot >= nums[h] && l < h) h--; nums[l] = nums[h]; while(pivot <= nums[l] && l < h) l++; nums[h] = nums[l]; } nums[l] = pivot; if (l == k) {return;} else if (l > k) {partition(nums, low, l - 1, k);} else {partition(nums, l + 1, high, k);} }}
参考文献
【1】使用快速排序方法求第K大的数_qq_42211773的博客-CSDN博客_求第k大的数