码迷,mamicode.com
首页 > 其他好文 > 详细

11-215. Kth Largest Element in an Array

时间:2019-05-31 01:07:55      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:lan   分析   targe   oat   example   discuss   div   float   oid   

题目描述:

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: 5

Example 2:

Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4

Note: 
You may assume k is always valid, 1 ≤ k ≤ array‘s length.

代码:

 1 class Solution:
 2     def findKthLargest(self, nums, k) -> int:
 3         # shuffle nums to avoid n*n
 4         random.shuffle(nums)
 5         return self.quickSelection(nums, 0, len(nums) - 1, len(nums) - k)
 6 
 7     def quickSelection(self, nums, start, end, k):
 8         if start > end:
 9             return float(inf)
10         pivot = nums[end]
11         left = start
12         for i in range(start, end):
13             if nums[i] <= pivot:
14                 # swip left and i
15                 nums[left], nums[i] = nums[i], nums[left]
16                 left += 1
17         nums[left], nums[end] = nums[end], nums[left]
18         if left == k:
19             return nums[left]
20         elif left < k:
21             return self.quickSelection(nums, left + 1, end, k)
22         else:
23             return self.quickSelection(nums, start, left - 1, k)

 

一个基于python的很好的分析:https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/301338/Python-or-tm-215

11-215. Kth Largest Element in an Array

标签:lan   分析   targe   oat   example   discuss   div   float   oid   

原文地址:https://www.cnblogs.com/tbgatgb/p/10952819.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!