Python PodstawyŁatwe

Sortowanie elementów tablicy według częstotliwości

Szczegółowy przewodnik i implementacja Python dla problemu „Sortowanie elementów tablicy według częstotliwości”.

Oświadczenie o problemie

Łatwe

Napisz funkcję sort_by_frequency(arr), która sortuje elementy tablicy według ich częstotliwości w kolejności malejącej. Jeśli dwa elementy mają tę samą częstotliwość, mniejszy element jest pierwszy. Zwróć posortowaną tablicę jako listę.

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

Przykłady

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?
Rozważ użycie struktur danych specyficznych dla tablic, takich jak zestawy lub sterty.
Edge Cases to Watch
  • Puste struktury wejściowe
  • Wejścia jednoelementowe
  • Duże granice liczbowe

Gotowy do rozwiązania?

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

Otwórz w Edytorze
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

Polecane zasoby Pythona

Poszerzaj swoją wiedzę dzięki powiązanym interaktywnym samouczkom, ściągawkom i porównaniom kodów.