-
Notifications
You must be signed in to change notification settings - Fork 312
Expand file tree
/
Copy path215_KthLargestElementArray.py
More file actions
38 lines (33 loc) · 910 Bytes
/
Copy path215_KthLargestElementArray.py
File metadata and controls
38 lines (33 loc) · 910 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: xuezaigds@gmail.com
class Solution(object):
# Simple way: O(nlogn)
def findKthLargest(self, nums, k):
return sorted(nums)[-k]
class Solution_2(object):
# QuickSelect, according to:
# http://www.cs.yale.edu/homes/aspnes/pinewiki/QuickSelect.html
# Heap implement by c++ can be found in c++ version.
def findKthLargest(self, nums, k):
pivot = nums[0]
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)
elif k > len(nums) - len(nums2):
return self.findKthLargest(nums2, k - (len(nums) - len(nums2)))
else:
return pivot
"""
[1]
1
[3,2,1,5,6,4]
2
[1,2,1,3,9]
2
"""