215. Kth Largest Element in an Array

Posted CodesKiller

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了215. Kth Largest Element in an Array相关的知识,希望对你有一定的参考价值。

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

For example,
Given [3,2,1,5,6,4] and k = 2, return 5.

Note: 
You may assume k is always valid, 1 ≤ k ≤ array‘s length.

 

本题有多种方法,第一种方法是先给数组排序,然后直接找到第k的元素,代码如下:

1 public class Solution {
2     public int findKthLargest(int[] nums, int k) {
3         Arrays.sort(nums);
4         return nums[nums.length-k];
5     }
6 }

第二种方法使用小顶堆来做,代码如下:

 1 public class Solution {
 2     public int findKthLargest(int[] nums, int k) {
 3         PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
 4         for(int num:nums){
 5             pq.add(num);
 6             if(pq.size()>k) pq.poll();
 7         }
 8         return pq.peek();
 9     }
10 }

本题比较高明的做法是使用快速选择,通过本题可以了解快速选择有个特点,就是可以从大到小排列,也可以从小到大排列,需要注意的是与target相等的情况;快速选择的思想是,设置一个target值,这里面默认最左面的值,然后设置两个指针,一个在最左面(除去target的位置),另一个在最右面,然后进行比较,把大于target的放在左面,把小于target放在右面,然后隔开。代码如下:

 1 public class Solution {
 2     public int findKthLargest(int[] nums, int k) {
 3         int left = 0;
 4         int right  =nums.length-1;
 5         while(true){
 6             int pos = partition(nums,left,right);
 7             if(pos==k-1) return nums[pos];
 8             else if(pos<k-1) left = pos+1;
 9             else right = pos-1;
10         }
11     }
12     public void swap(int[] nums,int i,int j){
13         int temp = nums[i];
14         nums[i] = nums[j];
15         nums[j] = temp;
16     }
17     public int partition(int[] nums,int left,int right){
18         int target = nums[left];
19         int l = left+1;
20         int r = right;
21         while(l<=r){
22             if(target>nums[l]&&target<nums[r]){
23                 swap(nums,l++,r--);
24             }
25             if(target<=nums[l]){
26                 l++;
27             }
28             if(target>=nums[r]){
29                 r--;
30             }
31         }
32         swap(nums,left,r);
33         return r;
34     }
35 }

 快速选择有一些需要注意的细节,网址如下:

https://comzyh.com/blog/archives/713/

以上是关于215. Kth Largest Element in an Array的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode-215. Kth Largest Element in an Array

#Leetcode# 215. Kth Largest Element in an Array

LeetCode OJ 215. Kth Largest Element in an Array 堆排序求解

LN : leetcode 215 Kth Largest Element in an Array

215. Kth Largest Element in an Array

215. Kth Largest Element in an Array