1636. Sort Array by Increasing Frequency ## 思路 用Counter計算num出現次數, 再用(cnt, -num) 做排序 ## Complexity Time: O(N logN) Space: O(N) ## Code Counter + Heap ```python class Solution: def frequencySort(self, nums: List[int]) -> List[int]: counter = Counter(nums) arr = [(cnt, -num) for num, cnt in counter.items()] heapq.heapify(arr) ans = [] while arr: cnt, num = heapq.heappop(arr) ans += [-num] * cnt return ans ``` Counter + Sorted ```python class Solution: def frequencySort(self, nums: List[int]) -> List[int]: counter = Counter(nums) return sorted(nums, key=lambda x: (counter[x], -x)) ``` -- ※ 發信站: 批踢踢實業坊(ptt-web.org.tw), 來自: 218.35.11.142 (臺灣) ※ 文章網址: https://ptt-web.org.tw/Marginalman/M.1721697662.A.185
sustainer123: 剩我寫超過3行 哇哇嗚嗚嗚 07/23 09:22