Kth Largest Element in an Array
2015-09-01 16:58
197 查看
题目:
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.
解题思路1:
第一反应就是先排序,再求出对应的数。
后来看到tags是,以后再改!!!!
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
nums.sort()
length = len(nums)
return nums[length-k]
思路2:
可以利用快排的思路解题
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.
解题思路1:
第一反应就是先排序,再求出对应的数。
后来看到tags是,以后再改!!!!
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
nums.sort()
length = len(nums)
return nums[length-k]
思路2:
可以利用快排的思路解题
class Solution { public: int findKthLargest(vector<int>& nums, int k) { int index = rand()%nums.size(), cur = nums[index]; vector<int> big, small; for(int i=0;i<nums.size();i++) { if(i==index)continue; if(nums[i]>=cur) big.push_back(nums[i]); else small.push_back(nums[i]); } if(big.size()==k-1) return cur; else if(big.size()>k-1) return findKthLargest(big,k); else return findKthLargest(small,k-1-big.size()); } };
相关文章推荐
- python基础练习笔记
- 9..IOS学习:用UIWindow自定义AlertView(最基本代码)
- 解决Cannot resolve symbol "styleable"的方法
- ffmpeg: error while loading shared libraries: libavdevice.so.56
- Unity3D的SerializeField 序列化域名
- POJ 1742 Coins (多重背包)
- HDU 2227 Find the nondecreasing subsequences(DP)
- iOS KVC,KVO
- JavaScript基础知识整理
- 从今天开始学习cocos 2d js
- log4j.properties 详解与配置步骤
- Bitwise AND of Numbers Range
- mysql 如何kill session
- 亿级用户下的新浪微博平台架构
- Masonry
- EXCEL去重统计(条件去重复计数)
- 面试题:23从上往下打印二叉树
- java线程研究---(7)Thread同步:多线程数据共用会产生问题
- web报告工具FineReport在使用方法和解决方案常见错误遇到(一)
- [Unity3d]定义自己的鼠标