The original title link is here: https://leetcode.com/problems/course-schedule-ii/
Course schedule is the advanced version of the topic. The same approach is used, where only one result is returned, so the traversed node is placed in an array.
AC Java:
1 Public classSolution {2 Public int[] FindOrder (intNumcourses,int[] Prerequisites) {3 int[] res =New int[numcourses];4List<set> adjancylist =NewArraylist<set>();5 for(inti = 0; i<numcourses; i++){6Adjancylist.add (NewHashset<integer>());7 }8 for(inti = 0; i<prerequisites.length; i++){9Adjancylist.get (Prerequisites[i][1]). Add (prerequisites[i][0]);Ten } One A int[] Countpost =New int[numcourses]; - for(inti = 0; I<adjancylist.size (); i++){ -Set<integer> Perset =Adjancylist.get (i); theIterator<integer> it =perset.iterator (); - while(It.hasnext ()) { -Countpost[it.next ()]++; - } + } - for(inti = 0; i<numcourses; i++){ + intK = 0; A while(k<countpost.length) { at if(Countpost[k] = = 0){ -COUNTPOST[K] = 1; - Break; - } -k++; - } in if(k = =countpost.length) { - return New int[0]; to } +Res[i] =K; -Set<integer> Desccount =Adjancylist.get (k); theIterator<integer> descit =desccount.iterator (); * while(Descit.hasnext ()) { $Countpost[descit.next ()]--;Panax Notoginseng } - } the returnRes; + } A}
Leetcode Course Schedule II