Kth largest element in an array
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
#print
#print 'nums: ', nums
first = 0
last = len(nums) - 1
pivotIndex = self.partition(nums, first, last)
#print 'pivotIndex = ', pivotIndex, ' pivotElem = ', nums[pivotIndex]
pivotsLargestPosition = len(nums) - pivotIndex
#print 'pivotsLargestPosition: ', pivotsLargestPosition, ' k: ', k
if pivotsLargestPosition == k:
return nums[pivotIndex]
elif pivotsLargestPosition < k:
return self.findKthLargest(nums[:pivotIndex], (k - pivotsLargestPosition))
else:
return self.findKthLargest(nums[pivotIndex+1:], (k))
def partition(self, nums, first, last):
pivot = nums[first] # choosing the pivot can be randomized
#print 'pivot chosen: ', pivot, ' index: ', first
leftPtr = first + 1
rightPtr = last
done = False
while not done:
while leftPtr <= rightPtr and nums[leftPtr] <= pivot:
leftPtr += 1
while rightPtr >= leftPtr and nums[rightPtr] >= pivot:
rightPtr -= 1
if rightPtr < leftPtr:
done = True
else:
temp = nums[rightPtr]
nums[rightPtr] = nums[leftPtr]
nums[leftPtr] = temp
temp = nums[rightPtr]
nums[rightPtr] = nums[first]
nums[first] = temp
return rightPtr # location of the pivotLast updated