Le migliori 150 intervisteFacile

Programma del corso II

Guida dettagliata e implementazione Python per il problema 'Programma del corso II'.

Dichiarazione del problema

Facile

Ci sono un totale di numCourses corsi che devi seguire, etichettati da 0 a numCourses - 1. Ti viene fornito un array prerequisites dove prerequisites[i] = [ai, bi] indica che devi prima seguire il corso bi se vuoi seguire il corso ai.

Restituisci l'ordine dei corsi che dovresti seguire per terminarli tutti. Se ci sono molte risposte valide, restituiscine qualcuna. Se è impossibile completare tutti i corsi, restituisce un array vuoto.

Scrivi una funzione findOrder(numCourses: int, prerequisites: List[List[int]]) -> List[int].

Vincoli
  • 1 <= numCourses <= 2000
  • 0 <= len(prerequisites) <= 5000
  • prerequisites[i].length == 2
  • 0 <= ai, bi < numCourses

Esempi

Example 1
Input
numCourses = 2, prerequisites = [[1,0]]
Output
[0,1]
Explanation

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1].

Example 2
Input
numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
Output
[0,2,1,3]
Explanation

There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].

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