【LeetCode】 215. Kth Largest Element in an Array
2017-01-16 07:58
381 查看
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
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
public class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
for (int num : nums) {
pq.offer(num);
if (pq.size() > k) {
pq.poll();
}
}
return pq.peek();
}
}
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.
public class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
for (int num : nums) {
pq.offer(num);
if (pq.size() > k) {
pq.poll();
}
}
return pq.peek();
}
}
public class Solution { public int findKthLargest(int[] nums, int k) { final int N = nums.length; Arrays.sort(nums); return nums[N - k]; } }
相关文章推荐
- 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)