[leetcode] 215. Kth Largest Element in an Array 解题报告
来源:互联网 发布:长波电台事件 知乎 编辑:程序博客网 时间:2024/06/04 04:17
题目链接:https://leetcode.com/problems/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.
思路:这题是利用了quick-select的算法,也就是快速排序的partition,这个方法的理论时间复杂度是O(n),是一种非常有用的工具.
使用分治每次将数组划分为两段,并且返回划分点的位置,如果这个位置恰好是我们要的第k大的数,那么返回这个数即可,
否则如果返回的位置小于要找的位置,则向右边的一半数组继续寻找
如果返回的位置大于要找的位置,则向左边寻找.
代码如下:
class Solution {public: int partition(vector<int>& nums, int left, int right) { int val = nums[right]; for(int i = left; i < right; i++) if(nums[i] < val) swap(nums[left++], nums[i]); swap(nums[right], nums[left]); return left; } int findKthLargest(vector<int>& nums, int k) { int len = nums.size(), left = 0, right = len-1, ans, pos = len-k; while((ans=partition(nums, left, right)) != pos) ans<pos?left = ans + 1: right = ans - 1; return nums[len-k]; }};
0 0
- [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-Kth Largest Element in an Array-解题报告
- 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
- 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
- LintCode:Add Two Numbers
- 条款
- 【12】AutoCompleteTextView——自动完成文本框
- 《Hadoop:The Definitive Guide 4th Edition》Chapter 17 Hive——B部分
- zoj2112 树状数组+主席树 区间动第k大
- [leetcode] 215. Kth Largest Element in an Array 解题报告
- poj3580 splay树 REVOVLE循环
- [BZOJ 1941]Hide and Seek
- C#中将调试信息记录到文件中去
- Haoop selfjoin 左表 右表 自连接
- 1037. 在霍格沃茨找零钱
- 如何解决某个端口被谁占用?
- 搭建C++开发开发环境
- 想做女性方面的手游