本质上是一样的解决方案,利用python的heapq 进行解题
[347] Top K Frequent Elements
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
heap=[]
dic={}
ret=[]
for num in nums:
if num not in dic:
dic[num]=1
else:
dic[num]+=1
for key,val in dic.items():
heapq.heappush(heap,(-val,key))
for i in range(k):
count,key=heapq.heappop(heap)
ret.append(key)
return ret
and use bucket sort
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
bucket=[[] for i in range(len(nums))]
dic={}
ret=[]
for num in nums:
if num not in dic:
dic[num]=1
else:
dic[num]+=1
for key in dic:
bucket[dic[key]-1].append(key)
for i in range(len(nums)-1,-1,-1):
for j in range(len(bucket[i])):
ret.append(bucket[i][j])
if len(ret)==k:
return ret
[692] Top K Frequent Words
class Solution(object):
def topKFrequent(self, words, k):
"""
:type words: List[str]
:type k: int
:rtype: List[str]
"""
dic={}
for i in words:
if i not in dic:
dic[i]=1
else:
dic[i]+=1
maxheap=[]
for val, count in dic.items():
heapq.heappush(maxheap,(-count,val))
ret=[]
for i in range(k):
cout,word=heapq.heappop(maxheap)
ret.append(word)
return ret
659. Split Array into Consecutive Subsequences
Example 1:
Input: [1,2,3,3,4,5]
Output: True
Explanation:
You can split them into two consecutive subsequences :
1, 2, 3
3, 4, 5
Example 2:
Input: [1,2,3,3,4,4,5,5]
Output: True
Explanation:
You can split them into two consecutive subsequences :
1, 2, 3, 4, 5
3, 4, 5
class Solution(object):
def isPossible(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
dic=collections.defaultdict(list)
#general idea is use heapq to store the ending element and the length
for n in nums:
if n-1 not in dic:
heapq.heappush(dic[n],1)
else:
l=heapq.heappop(dic[n-1])
if not dic[n-1]:
del dic[n-1]
heapq.heappush(dic[n],l+1)
for key,val in dic.items():
if heapq.heappop(val)<3:
return False
return True