Re: [閒聊] 每日leetcode

作者: dont   2024-07-23 09:21:00
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))
```
作者: sustainer123 (caster)   2024-07-23 09:22:00
剩我寫超過3行 哇哇嗚嗚嗚

Links booklink

Contact Us: admin [ a t ] ucptt.com