Sezione DSAFacile

Ricerca lineare

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

Dichiarazione del problema

Facile

Scrivi una funzione linear_search(arr, target) che accetta un elenco di numeri interi arr e un numero intero target. Esegue la scansione dell'elenco dall'inizio alla fine e restituisce l'indice in base 0 della prima occorrenza di target. Se target non è presente nell'elenco, restituisce -1.

Vincoli
  • 0 <= len(arr) <= 1000
  • -10^9 <= arr[i], target <= 10^9

Esempi

Example 1
Input
arr = [4, 2, 9, 1, 7], target = 9
Output
2
Explanation

The target 9 is found at index 2 of the list [4, 2, 9, 1, 7].

Example 2
Input
arr = [4, 2, 9, 1, 7], target = 5
Output
-1
Explanation

The target 5 is not present in the list, so we return -1.

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