LeetCode----Kth Largest Element in an Array
来源:互联网 发布:中科大软件学院考研 编辑:程序博客网 时间:2024/04/29 02:44
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.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
分析:
寻找数组中第k大的数。思路1:排序。思路2:利用快排的Partition。
代码1:
class Solution(object): def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ nums.sort() return nums[len(nums) - k]
代码2:
class Solution(object): def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ nums_len = len(nums) l = 1 r = nums_len while True: lo, pi, hi = self.partition(nums, l, r) nums = lo + [pi] + hi if nums_len - k == len(lo): return pi if nums_len - k > len(lo): l = len(lo) + 2 else: r = len(lo) def partition(self, nums, l, r): # 从第l个元素到第r个元素之间切割 left = nums[:l - 1] right = nums[r:] pi, seq = nums[l - 1], nums[l:r] lo = [x for x in seq if x <= pi] hi = [x for x in seq if x > pi] return left + lo, pi, hi + right
0 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
- 架构之路(一):目标
- showModelessDialog() 详解
- 单例模式
- 显示创建Mat对象的七种方法
- Web——WCF实现RESTFul Web Service
- LeetCode----Kth Largest Element in an Array
- 架构之路(二):性能
- curl模拟用户post测试
- Oracle 数据库基础知识点总结(一)
- BZOJ 4278 ONTAK2015 Tasowanie 后缀数组
- @Cacheable、@CachePut和@CacheEvict介绍
- JS对select及option的操作详解
- hdu5492(2015合肥网络赛I题)
- 架构之路(三) 单元测试