leetcode215. Kth Largest Element in an Array
2017-06-17 20:07
393 查看
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的优先队列public class Solution { public int findKthLargest(int[] nums, int k) { if (nums == null || nums.length == 0 || k > nums.length) { return -1; } PriorityQueue<Integer> pq = new PriorityQueue<>(); for (int num : nums) { pq.offer(num); if (pq.size() > k) { pq.poll(); } } return pq.peek(); } }
相关文章推荐
- LeetCode 215. Kth Largest Element in an Array(第K大元素)
- [leetcode] 215. Kth Largest Element in an Array
- leetcode 215. Kth Largest Element in an Array
- [leetcode] 215. Kth Largest Element in an Array
- leetcode刷题之旅——215. Kth Largest Element in an Array
- 215. Kth Largest Element in an Array LeetCode
- leetcode 215. Kth Largest Element in an Array
- leetcode 215. Kth Largest Element in an Array | Java最短代码实现
- Leetcode 215. Kth Largest Element in an Array[medium]
- 【leetcode】215. Kth Largest Element in an Array
- [leetcode]215. Kth Largest Element in an Array
- Leetcode 215. Kth Largest Element in an Array
- 【LeetCode】215. Kth Largest Element in an Array,基于Java和C++的解法
- LeetCode 215. Kth Largest Element in an Array
- [LeetCode]215. Kth Largest Element in an Array
- leetcode 215. Kth Largest Element in an Array
- [leetcode] 215. Kth Largest Element in an Array 解题报告
- LeetCode215. Kth Largest Element in an Array
- Leetcode 215. Kth Largest Element in an Array
- 【LeetCode】215. Kth Largest Element in an Array (Medium)