Le migliori 150 intervisteFacile

Cerca nell'array ordinato ruotato

Guida dettagliata e implementazione Python per il problema "Cerca nell'array ordinato ruotato".

Dichiarazione del problema

Facile

Esiste un array di numeri interi nums ordinato in ordine crescente (con valori distinti). Prima di essere passato alla funzione, nums viene eventualmente ruotato in corrispondenza di un indice pivot sconosciuto k (1 <= k < nums.length) in modo tale che l'array risultante sia [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]].

Dato l'array nums dopo l'eventuale rotazione e un intero target, restituisce l'indice di target se è in nums, o -1 se non è in nums.

È 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) <= 5000
  • -10^4 <= nums[i] <= 10^4
  • All values of nums are unique
  • nums is an ascending array that is possibly rotated
  • -10^4 <= target <= 10^4

Esempi

Example 1
Input
nums = [4, 5, 6, 7, 0, 1, 2], target = 0
Output
4
Explanation

0 is found at index 4.

Example 2
Input
nums = [4, 5, 6, 7, 0, 1, 2], target = 3
Output
-1
Explanation

3 is not in the array.

Example 3
Input
nums = [1], target = 0
Output
-1
Explanation

0 is not in the array.

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.