[勇者闯LeetCode] 215. Kth Largest Element in an Array
2017-03-05 21:07
537 查看
[勇者闯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,4and k=2, return 5.
Information
Tags: Heap | Divide and ConquerDifficulty: Medium
Solution
使用QuickSelect,算法复杂度O(N).from random import randint class 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
相关文章推荐
- LeetCode 215. Kth Largest Element in an Array(第K大元素)
- [leetcode] 215. Kth Largest Element in an Array
- leetcode 215. Kth Largest Element in an Array
- [leetcode] 215. Kth Largest Element in an Array
- leetcode刷题之旅——215. Kth Largest Element in an Array
- 215. Kth Largest Element in an Array LeetCode
- leetcode 215. Kth Largest Element in an Array
- leetcode 215. Kth Largest Element in an Array | Java最短代码实现
- Leetcode 215. Kth Largest Element in an Array[medium]
- 【leetcode】215. Kth Largest Element in an Array
- [leetcode]215. Kth Largest Element in an Array
- Leetcode 215. Kth Largest Element in an Array
- 【LeetCode】215. Kth Largest Element in an Array,基于Java和C++的解法
- LeetCode 215. Kth Largest Element in an Array
- [LeetCode]215. Kth Largest Element in an Array
- leetcode 215. Kth Largest Element in an Array
- [leetcode] 215. Kth Largest Element in an Array 解题报告
- LeetCode215. Kth Largest Element in an Array
- Leetcode 215. Kth Largest Element in an Array
- 【LeetCode】215. Kth Largest Element in an Array (Medium)