Leetcode 215. Kth Largest Element in an Array
来源:互联网 发布:淘宝如何清空收藏夹 编辑:程序博客网 时间:2024/06/03 17:30
215. Kth Largest Element in an Array
Total Accepted: 81842 Total Submissions: 226913 Difficulty: MediumFind 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.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Hide Similar Problems
思路:
看到top kth,直接反应就是heap。
用一个最大堆,然后放入元素,第K次取的元素就是所求。
运行时间:16ms。
public class Solution { public int findKthLargest(int[] nums, int k) { PriorityQueue<Integer> heap = new PriorityQueue<Integer>(Collections.reverseOrder()); for(int item : nums) heap.offer(item); int count = 0; while(count < k){ int item = heap.poll(); count++; if(count == k) return item; } return -1; }}
然后一看标签是分治。那好现在nums的k,就等于nums删除最大元素的k -1,直到k==1。
于是最后一定是最大元素。于是一定要sort。那么sort之后直接无视分治取出相应位置元素就可以了。
运行时间:5ms。
public class Solution { public int findKthLargest(int[] nums, int k) { Arrays.sort(nums); return nums[nums.length - k]; }}
0 0
- Leetcode Kth Largest Element in an Array
- Leetcode: Kth Largest Element in an Array
- LeetCode Kth Largest Element in an Array
- [LeetCode] Kth Largest Element in an Array
- [leetcode] Kth Largest Element in an Array
- leetcode--Kth Largest Element in an Array
- #leetcode#Kth Largest Element in an Array
- LeetCode Kth Largest Element in an Array
- 【Leetcode】Kth Largest Element in an Array
- Leetcode: Kth Largest Element in an Array
- Kth Largest Element in an Array -- leetcode
- [Leetcode]Kth Largest Element in an Array
- [LeetCode]Kth Largest Element in an Array
- *LeetCode-Kth Largest Element in an Array
- LeetCode----Kth Largest Element in an Array
- LeetCode Kth Largest Element in an Array
- leetcode-Kth Largest Element in an Array
- LeetCode -- Kth Largest Element in an Array
- Leetcode 341. Flatten Nested List Iterator
- Python.微信
- C++创建文件夹
- 关于Windows用Task Scheduling执行C++ exe文件
- 10.Doctrine2 (2)
- Leetcode 215. Kth Largest Element in an Array
- [LeetCode]100. Same Tree
- spring aop(面向切面) 详解
- vec
- HashCode 和 Equals 的使用 - 使用自定义对象作为HashMap的Key例子
- 项目管理之甘特图
- 這是我的java程序之路的開始
- poj 2356 poj3370
- [LeetCode]1. Two Sum