Sezione DSAFacile

Elemento di maggioranza

Guida dettagliata e implementazione Python per il problema 'Majority Element'.

Dichiarazione del problema

Facile

Scrivi una funzione find_majority_element(arr) che accetta un elenco di numeri interi arr e restituisce l'elemento di maggioranza (l'elemento che appare più di n // 2 volte). Si può supporre che l'elemento maggioritario esista sempre nell'array.

Vincoli
  • 1 <= len(arr) <= 5 * 10^4
  • -10^9 <= arr[i] <= 10^9

Esempi

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

3 appears twice, which is more than 3 // 2 = 1 time.

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

2 appears 4 times, which is more than 7 // 2 = 3 times.

Need a Hint?
Prendi in considerazione l'utilizzo di strutture dati specifiche degli array come set o heap.
Edge Cases to Watch
  • Strutture di input vuote
  • Ingressi a elemento singolo
  • Grandi limiti numerici

Pronto a risolvere?

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

Apri nell'editor
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

Risorse Python consigliate

Espandi le tue conoscenze con tutorial interattivi, foglietti illustrativi e confronti di codici correlati.