LeetCode-Kth Largest Element in an Array-解题报告
来源:互联网 发布:淘宝网装饰腰带 编辑:程序博客网 时间:2024/06/05 04:34
原链接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.
类似快速排序,选取第一个元素作为分界元素,快速排序后
s...i...e
如果i - s + 1 == k return nums[i]
如果i-s + 1 > k return find_k_largest(nums, k, s, i - 1);
其他情况 return find_k_largest(nums, k - (i - s + 1), i + 1, e);
当然了你也可以随机选取一个元素作为参考元素
<span style="font-size:14px;">class Solution {public: int findKthLargest(vector<int>& nums, int k) {return find_k_largest(nums, k, 0, nums.size() - 1);}int find_k_largest(vector<int>& nums, int k, int s, int e){int i = s, j = e, tmp = nums[i];while (i < j){while (i < j && nums[j] <= tmp)--j;nums[i] = nums[j];while (i < j && nums[i] > tmp)++i;nums[j] = nums[i];}nums[i] = tmp;if (i - s + 1 == k)return nums[i];else if(i - s + 1 > k)return find_k_largest(nums, k, s, i - 1);else return find_k_largest(nums, k - (i - s + 1), i + 1, e);}};</span>
0 0
- LeetCode-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 解题报告
- 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
- c语言“贪吃蛇”
- 【POJ 1789】Truck History
- EF和LINQ 调用存储过程
- 通过字节码分析java中的switch语句
- Android ListView 多种布局--初步
- LeetCode-Kth Largest Element in an Array-解题报告
- Python 闭包
- Watcher实现机制之服务端处理
- OpenNebula
- Eclipse中安装vim插件
- 猜猜看1(显示图片)
- linux命令学习:iptables详解1
- 主成分分析算法
- 黑马程序员---面向对象与面向过程