Python GrundlagenEinfach

Elemente eines Arrays nach Häufigkeit sortieren

Detaillierte Anleitung und Python-Implementierung für das Problem „Elemente eines Arrays nach Häufigkeit sortieren“.

Problemstellung

Einfach

Schreiben Sie eine Funktion sort_by_frequency(arr), die Elemente des Arrays nach ihrer Häufigkeit in absteigender Reihenfolge sortiert. Wenn zwei Elemente die gleiche Frequenz haben, kommt das kleinere Element zuerst. Gibt das sortierte Array als Liste zurück.

Einschränkungen
  • 1 <= len(arr) <= 10^5
  • -10^6 <= arr[i] <= 10^6

Beispiele

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?
Erwägen Sie die Verwendung von Array-spezifischen Datenstrukturen wie Sets oder Heaps.
Edge Cases to Watch
  • Leere Eingabestrukturen
  • Einzelelementeingaben
  • Große numerische Grenzen

Bereit zur Lösung?

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

Im Editor öffnen
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

Empfohlene Python-Ressourcen

Erweitern Sie Ihr Wissen mit zugehörigen interaktiven Tutorials, Spickzetteln und Codevergleichen.