[勇者闯LeetCode] 215. Kth Largest Element in an Array
来源:互联网 发布:自卫武器 知乎 编辑:程序博客网 时间:2024/05/17 15:20
[勇者闯LeetCode] 215. Kth Largest Element in an Array
Description
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.
Information
- Tags: Heap | Divide and Conquer
- Difficulty: Medium
Solution
使用QuickSelect,算法复杂度O(N).
from random import randintclass Solution(object): def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ obj = k - 1 l, r = 0, len(nums)-1 while l <= r: pivot_idx = randint(l, r) new_pivot_idx = self.partition(nums, l, r, pivot_idx) if new_pivot_idx == obj: return nums[new_pivot_idx] elif new_pivot_idx > obj: r = new_pivot_idx - 1 else: l = new_pivot_idx + 1 def partition(self, nums, l, r, pivot_idx): pivot_value = nums[pivot_idx] new_pivot_idx = l nums[pivot_idx], nums[r] = nums[r], nums[pivot_idx] for i in range(l, r): if nums[i] > pivot_value: nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i] new_pivot_idx += 1 nums[r], nums[new_pivot_idx] = nums[new_pivot_idx], nums[r] return new_pivot_idx
0 0
- [勇者闯LeetCode] 215. 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
- *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
- viewpager同步
- threejs设置对象层次
- 数据结构 树、二叉树、完全二叉树
- 如何在Windows下安装gensim
- LeetCode : Number of Boomerangs
- [勇者闯LeetCode] 215. Kth Largest Element in an Array
- zookeeper 安装 windows环境
- php面试常用题目精解(二)
- 【九度OJ】题目1064:反序数 解题报告
- 【VMware】虚拟机中的linux安装
- Spring入门hello world常见问题及解决办法
- 【struts基础】核心配置文件struts.xml介绍
- threejs渲染器剔除模式
- J2SE的13个规范