Leetcode 215. Kth Largest Element in an Array
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.
Example 1:
Input:[3,2,1,5,6,4]and k = 2 Output: 5Example 2:
Input:[3,2,3,1,2,4,5,5,6]and k = 4 Output: 4
不太懂这个题目的意思,我的解法是直接数组排序然后输出第k位的数,代码如下:
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
temp = sorted(nums, reverse = True)
return temp[k-1]
beat 90%+
去看了一下Discussion ,发现果然是自己想法太简单不适合工程了
如果数组size很小,直接sort,如果数组非常大,那么时间复杂度为O(nlogn)的算法就不太好了。
同时,虽然Accepted了,我还是要需要检测一下nums数组中的元素是否为0个或者不存在,即
if (nums == null || nums.length == 0) return Integer.MAX_VALUE;
解法一: 使用MaxHeap&MinHeap
是Python语言写的使用MinHeap 和 MaxHeap的两种解法较为清晰的解析,还有比较两种堆实现的时间复杂度和空间复杂度对比。
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/301338/Python-or-tm-215
备注:float('inf')是获取正无穷
解法二:分治思想 Quick Select
较为elegant的代码
想法:
1.选定一个数值作为pivot,进行快排
2.通过快排重整数组使得pivot前的数大,pivot后的数小,同时返回pivot的位置
3.通过得到pivot的位置和k-1比较,如果刚好返回pivot值,如果k-1小则寻找(left,pivot.pos-1)位置,如果k-1大则寻找(pivot.pos+1,right)的位置.
def findKthLargest(self, nums, k):
return self.quickSelect(nums, 0, len(nums)-1, k)
def quickSelect(self, nums, start, n, k): # quick select
pos = self.partition(nums, start, n)
if pos == k-1:
return nums[pos]
elif pos >= k:
return self.quickSelect(nums, start, pos - 1, k)
return self.quickSelect(nums, pos + 1, n, k)
def partition(self, nums, left, right):
pivot = nums[right] # pick the last one as pivot
i = left
for j in xrange(left, right): # left to right -1
if nums[j] > pivot: # the larger elements are in left side
nums[j], nums[i] = nums[i], nums[j]
i += 1
nums[right], nums[i] = nums[i], nums[right] # swap the i and the last element
return i
这个思想挺好的讲解和拓展:
939

被折叠的 条评论
为什么被折叠?



