Created
July 17, 2020 08:17
-
-
Save RP-3/35cd909992958c8db6c3aeb395a54c97 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
from collections import defaultdict | |
# quickSelect | |
# n = len(list) | |
# k = discintElementsInList | |
# O(n + k) | |
class Solution: | |
def topKFrequent(self, nums: List[int], k: int) -> List[int]: | |
counts = defaultdict(int) | |
for n in nums: | |
counts[n]+=1 | |
countList = [(count, num) for num, count in counts.items()] | |
l, r = 0, len(countList)-1 | |
while(l <= r): | |
mid = self.partition(countList, l, r) | |
if mid < k-1: | |
l = mid+1 | |
elif mid > k-1: | |
r - mid-1 | |
else: | |
return [num for count, num in countList[0:mid+1]] | |
def partition(self, nums, l, r): | |
pivotIndex = random.randint(l, r) | |
pivot, rightEnd = nums[pivotIndex], r | |
nums[pivotIndex], nums[r] = nums[r], nums[pivotIndex] | |
r-=1 | |
while(l <= r): | |
if(nums[l][0] >= pivot[0]): | |
l+=1 | |
else: | |
nums[l], nums[r] = nums[r], nums[l] | |
r-=1 | |
nums[rightEnd], nums[l] = nums[l], nums[rightEnd] | |
return l | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment