欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

LeetCode-215.KthLargestElementinanArray[C++][Java]

时间:2023-06-10

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& nums, int k) { if (k <= 0 || k > nums.size()) {return -1;} k--; int l = 0, h = nums.size() - 1, idx = partition(nums, l, h); while(idx != k ) { if(idx < k) { idx = partition(nums, idx+1, h); } else { idx = partition(nums, l, idx-1); } } return nums[k]; } int partition(vector& nums, int l, int h) { int pivot = nums[l]; while(l < h) { while(pivot>=nums[h] && l

2、递归

class Solution {public: int findKthLargest(vector& nums, int k) { if (k <= 0 || k > nums.size()) {return -1;} partition(nums, 0, nums.size() - 1, --k); return nums[k]; } void partition(vector& nums, int l, int h, int k) { int pivot = nums[l], low = l, high = h; while(l < h) { while(pivot>=nums[h] && l k) {partition(nums, low, l - 1, k);} else {partition(nums, l + 1, high, k);} }};

【Java】

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大的数

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。