Programmazione competitivaFacile

Contare 1 nell'array binario

Guida dettagliata e implementazione Python per il problema "Conteggio 1 nell'array binario".

Dichiarazione del problema

Facile

Scrivi una funzione count_ones(arr) che accetta un array binario arr ordinato in ordine decrescente (dove tutti gli 1 appaiono prima di tutti gli 0) e restituisce il conteggio degli 1 nell'array. La soluzione dovrebbe essere eseguita in tempo O(log n).

Vincoli
  • 0 <= len(arr) <= 10^5
  • arr[i] is either 0 or 1

Esempi

Example 1
Input
count_ones([1, 1, 1, 1, 0, 0, 0])
Output
4
Explanation

There are four 1s at the beginning of the array.

Example 2
Input
count_ones([1, 1, 0, 0, 0])
Output
2
Explanation

There are two 1s at the beginning of the array.

Need a Hint?
Prendi in considerazione l'utilizzo di strutture dati specifiche per la ricerca e l'ordinamento 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.