Re: [閒聊] 每日leetcode已刪文
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.cc), 來自: 218.35.11.142 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1721697662.A.185.html
推
07/23 09:22,
1年前
, 1F
07/23 09:22, 1F
討論串 (同標題文章)
完整討論串 (本文為第 548 之 1548 篇):