Given a list, find the k-th largest element in the list.
Input: list = [3, 5, 2, 4, 6, 8], k = 3
Output: 5
def findKthLargest(nums, k):
pass
print(findKthLargest([3, 5, 2, 4, 6, 8], 3))
# 5
I found two ways to solve this. First we would be sorting the array. So all we'd have to do is return the k-last index.
def findKthLargest1(nums, k):
nums.sort()
return nums[-k]
but there is a more interesting way to solve this problem, we can use Heaps. In general, when you hear about "smallest" or "largest". You should think: I need Heaps.
import heapq
def findKthLargest2(nums, k):
minHeap = []
heapq.heapify(minHeap)
for x in nums:
heapq.heappush(minHeap, x)
if len(minHeap) > k:
heapq.heappop(minHeap)
return heapq.heappop(minHeap);
您还可以使用:
sorted(my_list)[-k]
sorted function sorts items in ascending order by default. You call also define reverse parameter (set True for descending order) and get the kth largest:
sorted(nums, reverse=True)[k-1]
try to do in time complexity < (n log n)
All solutions provided have n log n complexity.
The following code
def findKthLargest(nums, k):
for _ in range(k):
s = max(nums)
t.remove(s)
return s
will require 2(kn - k(k - 1)/2) operations, so its complexity is O(kn). If k is a constant (not a function of n), complexity is linear O(n). If k is a function of n but k < log n for all k, n, complexity is still < n log n. And if k = O(n) then complexity is O(n^2) which is > n log n and sorting will work faster.
k = int(input()) l = [6,2,1,9,5] l.sort() print(l[-k])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.