LeetCode 215:Kth Largest Element in an Array
来源:互联网 发布:java ee eclipse 编辑:程序博客网 时间:2024/06/05 07:06
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.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
代码如下:
class Solution {public: int findKthLargest(vector<int>& nums, int k) { int length = nums.size(); if (length == 1) { return nums[0]; } vector<int> left; vector<int> right; for (int index=1; index<length; index++) { if (nums[index] > nums[0]) { right.push_back(nums[index]); }else{ left.push_back(nums[index]); } } length = right.size(); if (length >=k) { return findKthLargest(right, k); }else if(length == k-1){ return nums[0]; }else{ return findKthLargest(left, k-length-1); } }};
LeetCode对时间要求不高,下面这样的代码也能通过:
class Solution {public: int findKthLargest(vector<int>& nums, int k) { sort(nums.begin(), nums.end()); reverse(nums.begin(), nums.end()); return nums[k-1]; }};
1 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
- Android中View绘制流程以及invalidate()等相关方法分析
- 堆栈顺序存储结构实现3——遍历查看个数元素
- C++运算符重载(12) - 重载数组索引操作符[]
- android 实现手机方向识别
- nagios插件之监控多个tomcat线程数
- LeetCode 215:Kth Largest Element in an Array
- OpenWRT 路由配置技巧
- Android学习之 Scroller的介绍与使用
- Golang学习笔记--log包
- 仿小米MIUI卸载APP的动画(NineOld实现)
- C++异常(1) - 异常介绍
- 计算机网络各层协议
- Hadoop之——有趣问答(一)
- 如何在TableViewController中得到触摸点坐标