Python 基礎知識簡單

按頻率對數組元素進行排序

“按頻率對數組元素進行排序”問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 sort_by_frequency(arr),依頻率降序對陣列元素進行排序。如果兩個元素具有相同的頻率,則較小的元素在前。將排序後的陣列作為列表傳回。

約束條件
  • 1 <= len(arr) <= 10^5
  • -10^6 <= arr[i] <= 10^6

範例

Example 1
Input
arr = [1, 1, 2, 2, 2, 3]
Output
[2, 2, 2, 1, 1, 3]
Explanation

2 appears 3 times (most frequent), 1 appears 2 times, 3 appears 1 time.

Example 2
Input
arr = [4, 4, 5, 5, 6]
Output
[4, 4, 5, 5, 6]
Explanation

4 and 5 both appear 2 times; 4 < 5 so 4 comes first. 6 appears once.

Example 3
Input
arr = [9, 9, 9]
Output
[9, 9, 9]
Explanation

Only one distinct element.

Need a Hint?
考慮使用特定於數組的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。