LeetCode:215. Kth Largest Element in an Array

Medium

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.

Example 1:

Input: [3,2,1,5,6,4] and k = 2
Output: 5

Example 2:

Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4

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

解法一:(快排)

最傻瓜快速的解法,直接一次快排,然后返回第len-k位上的值即可。

    public int findKthLargest(int[] nums, int k) {
        Arrays.sort(nums) ;
        return nums[nums.length - k] ;
    }

解法二:(小顶堆)

维护一个小顶堆,依次将数组中的元素插入到堆中。因为小顶堆天然保证元素的有序性(从小到大),所以每次在插入元素后检查堆大小是否超过k。如超过,直接移除堆顶(也就是元素值最小的那个)。全部插入完毕后,直接返回堆顶即可。

	 public int findKthLargest(int[] nums, int k) {
	     Queue<Integer> heap = new PriorityQueue<>() ;
	     for(int num : nums) {
	         heap.add(num) ;
	         if(heap.size() > k) {
	             heap.poll() ;
	         }
	         
	     } 
	     
	     return heap.poll() ;
	 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yexianyi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值