Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from collections import Counter
- def kth_largest_in_an_array(numbers, k):
- import random
- kthindex=len(numbers)-k
- start=0
- end=len(numbers)-1
- def helper(start,end):
- if start==end:
- return
- pivot=random.randint(start,end)
- numbers[start],numbers[pivot]=numbers[pivot],numbers[start]
- # elemenst less than numbers[pivot] will be placed before pivotloc1
- # elemenst equal to numbers[pivot] will be placed between pivotloc1 and pivotloc2
- # elemenst greater than numbers[pivot] will be placed after pivotloc2
- pivotloc1 = start
- pivotloc2 = start
- for i in range(start+1,end+1):
- if numbers[i] < numbers[start]:
- pivotloc1+=1
- pivotloc2+=1
- numbers[pivotloc1],numbers[i]=numbers[i],numbers[pivotloc1]
- elif numbers[i] == numbers[start]:
- pivotloc2+=1
- numbers[pivotloc2],numbers[i]=numbers[i],numbers[pivotloc2]
- numbers[start],numbers[pivotloc1]=numbers[pivotloc1],numbers[start]
- # kth largest element is equal to numbers[pivot] if kthindex is between pivotloc1 and pivotloc2
- if pivotloc1 <= kthindex and kthindex <= pivotloc2:
- return
- elif pivotloc2 > kthindex:
- helper(start,pivotloc2-1)
- else:
- helper(pivotloc1+1,end)
- helper(start,end)
- return numbers[kthindex]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement