您的位置:首页 > 编程语言 > Go语言

[勇者闯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,4
and k=2, return 5.

Information

Tags: Heap | Divide and Conquer

Difficulty: 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithm leetcode