Le migliori 150 intervisteFacile

Ricerca binaria

Guida dettagliata e implementazione Python per il problema della "ricerca binaria".

Dichiarazione del problema

Facile

Dato un array di numeri interi nums ordinato in ordine crescente e un numero intero target, scrivere una funzione per cercare target in nums. Se target esiste, restituisce il suo indice. Altrimenti, restituisci -1.

È necessario scrivere un algoritmo con complessità di runtime O(log n).

Scrivi una funzione search(nums: List[int], target: int) -> int.

Vincoli
  • 1 <= len(nums) <= 10^4
  • -10^4 < nums[i], target < 10^4
  • All integers in nums are unique
  • nums is sorted in ascending order

Esempi

Example 1
Input
nums = [-1, 0, 3, 5, 9, 12], target = 9
Output
4
Explanation

9 exists in nums and its index is 4.

Example 2
Input
nums = [-1, 0, 3, 5, 9, 12], target = 2
Output
-1
Explanation

2 does not exist in nums so return -1.

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