1. sort重写
默认从大到小 x>y 返回true
class mysort(list):
def __lt__(self, other):
if self[1] > other[1]:
return True
if self[1] < other[1]:
return False
if self[1] == other[1]:
return self[0] < other[0]
class Solution:
"""
@param array: the input array
@return: the sorted array
"""
def multiSort(self, array):
# Write your code here
array.sort(key = mysort)
return array
堆也可以用该方案
小根堆,按照times大, name小的顺序动态更新堆
class node:
def __init__(self, times, name):
self.times = times
self.name = name
def __lt__(self, other):
if self.times != other.times:
return self.times < other.times
return self.name > other.name
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
hMap = collections.Counter(words)
heap = []
for name, times in hMap.items():
heapq.heappush(heap, node(times, name))
if len(heap) > k:
heapq.heappop(heap)
heap.sort()
heap = [i.name for i in heap]
heap.reverse()
return heap