Topic links: https://leetcode-cn.com/problems/kth-largest-element-in-an-array/ )
Subject description:
Find the unsorted array k largest elements. Please note that you need to find is the first k largest elements in the array is sorted, rather than the k distinct elements.
Example:
Example 1:
输入: [3,2,1,5,6,4] 和 k = 2
输出: 5
Example 2:
输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4
Description:
You may assume that k is always active, and 1 ≤ k ≤ length of the array.
Ideas:
Sort by title
Thinking a: \ (nlog (the n-) \) Sort
Two ideas: \ (nlog (k) \) heapsort
- Library Functions
- Handwriting heap row
Three ideas: The average time \ (O (n-) \) , the worst \ (O (n ^ 2) \) fast discharge portion
Each time a quick drain can be fixed number of positions, can be determined whether only looking at the position of!
Code:
A thought: Sort
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
return sorted(nums, reverse = True)[k - 1]
Thinking two: heapsort
1, library functions
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
return heapq.nlargest(k, nums)[-1]
Thinking two:
2, handwriting
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
def adjust_heap(idx, max_len):
left = 2 * idx + 1
right = 2 * idx + 2
max_loc = idx
if left < max_len and nums[max_loc] < nums[left]:
max_loc = left
if right < max_len and nums[max_loc] < nums[right]:
max_loc = right
if max_loc != idx:
nums[idx], nums[max_loc] = nums[max_loc], nums[idx]
adjust_heap(max_loc, max_len)
# 建堆
n = len(nums)
for i in range(n // 2 - 1, -1, -1):
adjust_heap(i, n)
#print(nums)
res = None
for i in range(1, k + 1):
#print(nums)
res = nums[0]
nums[0], nums[-i] = nums[-i], nums[0]
adjust_heap(0, n - i)
return res
Thinking three: fast row
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
def partition(left, right):
pivot = nums[left]
l = left + 1
r = right
while l <= r:
if nums[l] < pivot and nums[r] > pivot:
nums[l], nums[r] = nums[r], nums[l]
if nums[l] >= pivot:
l += 1
if nums[r] <= pivot:
r -= 1
nums[r], nums[left] = nums[left], nums[r]
return r
left = 0
right = len(nums) - 1
while 1:
idx = partition(left, right)
if idx == k - 1:
return nums[idx]
if idx < k - 1:
left = idx + 1
if idx > k - 1:
right = idx - 1