leetcode215:Kth Largest Element in an Array
程序员文章站
2022-04-25 11:45:11
...
思路:参考TopK的Quick Select做法https://blog.csdn.net/Somnus_k/article/details/82724704
代码:
public class KthLargestElementinanArray {
public static void main(String[] args) {
int[] arr = { 1, 8, 35, 4, 7 };
System.out.println(findKthLargest(arr, 4));
}
public static int findKthLargest(int[] nums, int k) {
return quickSelect(nums,k,0,nums.length-1);
}
private static int quickSelect(int[] nums, int k, int i, int j) {
if(i>=j)
return nums[i];
int index = partion(nums,i,j);
if(index-i+1==k)
return nums[index];
else if(index-i+1>k)
return quickSelect(nums, k, i, index-1);
else
return quickSelect(nums, k-(index-i+1), index+1, j);
}
private static int partion(int[] nums, int i, int j) {
int tmp = nums[i];
while(i<j){
while(i<j)
if(nums[j]>tmp)
{
nums[i]=nums[j];
i++;
break;
}else
j--;
while(i<j)
if(nums[i]<tmp)
{
nums[j]=nums[i];
j--;
break;
}else
i++;
}
nums[i]=tmp;
return i;
}
}
输出:
推荐阅读
-
5. Kth Largest Element
-
Kth Largest Element in an Array Leetcode #215 题解[C++]
-
215. Kth Largest Element in an Array
-
LeetCode 215 Kth Largest Element in an Array
-
LeetCode 215. Kth Largest Element in an Array
-
LeetCode算法问题14 —— Kth Largest Element in an Array
-
215. Kth Largest Element in an Array(返回数组中第几大元素)(leetcode)
-
LeetCode 215 -- 数组中的第K个最大元素 ( Kth Largest Element in an Array ) ( C语言版 )
-
Kth Largest Element in an Array解题报告
-
215[Medium]:Kth Largest Element in an Array