GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — leetcode/python/215_Kth_Largest_Element_in_an_Array.py at master · qiyuangong/leetcode

Expand file tree

/

215_Kth_Largest_Element_in_an_Array.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
40 lines (37 loc) · 1.26 KB
/

215_Kth_Largest_Element_in_an_Array.py

Copy path

File metadata and controls

40 lines (37 loc) · 1.26 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
39
40
class Solution(object):
# def findKthLargest(self, nums, k):
# """
# :type nums: List[int]
# :type k: int
# :rtype: int
# """
# return sorted(nums, reverse=True)[k - 1]
# def findKthLargest(self, nums, k):
# # build min heap
# heapq.heapify(nums)
# # remove n - k smallest number
# while len(nums) > k:
# heapq.heappop(nums)
# return nums[0]
# #return heapq.nlargest(k, nums)[-1]
def findKthLargest(self, nums, k):
# shuffle nums to avoid n*n
random.shuffle(nums)
return self.quickSelection(nums, 0, len(nums) - 1, len(nums) - k)
def quickSelection(self, nums, start, end, k):
if start > end:
return float('inf')
pivot = nums[end]
left = start
for i in range(start, end):
if nums[i] <= pivot:
# swip left and i
nums[left], nums[i] = nums[i], nums[left]
left += 1
nums[left], nums[end] = nums[end], nums[left]
if left == k:
return nums[left]
elif left < k:
return self.quickSelection(nums, left + 1, end, k)
else:
return self.quickSelection(nums, start, left - 1, k)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.