Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Created October 23, 2017 18:29
Show Gist options
  • Save cixuuz/f452e195b2c1e5a2a377a64623c1c7c3 to your computer and use it in GitHub Desktop.
Save cixuuz/f452e195b2c1e5a2a377a64623c1c7c3 to your computer and use it in GitHub Desktop.
[215. Kth Largest Element in an Array] #leetcode
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
# O(n) time, quick selection
# convert the kth largest to smallest
return self.findKthSmallest(nums, len(nums)+1-k)
def findKthSmallest(self, nums, k):
if nums:
pos = self.partition(nums, 0, len(nums)-1)
if k > pos+1:
return self.findKthSmallest(nums[pos+1:], k-pos-1)
elif k < pos+1:
return self.findKthSmallest(nums[:pos], k)
else:
return nums[pos]
# choose the left-most element as pivot
def partition(self, nums, l, r):
low = l
while l < r:
if nums[l] < nums[r]:
nums[l], nums[low] = nums[low], nums[l]
low += 1
l += 1
nums[low], nums[r] = nums[r], nums[low]
return low
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment