经典题目,quicksort 是O(n),没想明白。。。觉得还是on average在做2分啊
heap 方法是 n*O(k)
import random
class Solution:
# @param {integer[]} nums
# @param {integer} k
# @return {integer}
def findKthLargest(self, nums, k):
pivot = random.choice(nums)
nums1, nums2 = [], []
for num in nums:
if num > pivot:
nums1.append(num)
elif num < pivot:
nums2.append(num)
if k <= len(nums1):
return self.findKthLargest(nums1, k)
if k > len(nums) - len(nums2):
return self.findKthLargest(nums2, k - (len(nums) - len(nums2)))
return pivot
##另外java heap的做法
public class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue
heap = new PriorityQueue
();
for(int n:nums){
if(heap.size() < k ){
heap.add(n);
}else{
if(n > heap.peek()){
heap.poll();
heap.add(n);
}
}
}
return heap.peek();
}
}