150 najlepszych wywiadówŁatwe

Top K częstych elementów

Szczegółowy przewodnik i implementacja Python dla problemu „K najczęściej występujących elementów”.

Oświadczenie o problemie

Łatwe

Biorąc pod uwagę tablicę liczb całkowitych nums i liczbę całkowitą k, zwróć najczęściej używane elementy k. Odpowiedź możesz zwrócić w dowolnej kolejności.

Napisz funkcję topKFrequent(nums: List[int], k: int) -> List[int].

Ograniczenia
  • 1 <= len(nums) <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • k is in the range [1, number of unique elements in nums]
  • The answer is guaranteed to be unique

Przykłady

Example 1
Input
nums = [1, 1, 1, 2, 2, 3], k = 2
Output
[1, 2]
Explanation

1 appears 3 times and 2 appears 2 times. These are the 2 most frequent elements.

Example 2
Input
nums = [1], k = 1
Output
[1]
Explanation

There is only one element, so it is the most frequent.

Need a Hint?
Rozważ użycie struktur danych specyficznych dla tablic i haszowania, 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.