LeetCode-Kth Largest Element in an Array-解题报告
2015-06-29 23:15
591 查看
原链接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
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>
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>
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- C++中拷贝构造函数的应用详解
- C++中引用(&)的用法与应用实例分析
- C++使用CriticalSection实现线程同步实例
- C++智能指针实例详解
- 解析C++ 浮点数的格式化输出