[英]Find the k-th largest element in the list
Given a list, find the k-th largest element in the list. 给定一个列表,在列表中找到第k个最大元素。
Input: list = [3, 5, 2, 4, 6, 8], k = 3
输入:列表= [3、5、2、4、6、8],k = 3
Output: 5
输出: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.
因此,我们要做的就是返回k-last索引。
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. sorted函数默认情况下按升序对项目进行排序。 You call also define reverse parameter (set True for descending order) and get the kth largest:
您还调用了定义反向参数(将降序设置为True)并获得第k个最大值:
sorted(nums, reverse=True)[k-1]
try to do in time complexity < (n log n)
尝试做时间复杂度<(n log n)
All solutions provided have n log n complexity. 提供的所有解决方案都具有n log n的复杂性。
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). 将需要2(kn-k(k-1)/ 2)个运算,因此其复杂度为O(kn)。 If k is a constant (not a function of n), complexity is linear O(n).
如果k为常数(不是n的函数),则复杂度为线性O(n)。 If k is a function of n but k < log n for all k, n, complexity is still < n log n.
如果k是n的函数,但对于所有k,n,k <log n,则复杂度仍<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 = O(n),则复杂度为O(n ^ 2),即> n log n,排序将更快。
k = int(input()) l = [6,2,1,9,5] l.sort() print(l[-k])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.