Simple Java Solution


  • 1
    Z
    import java.util.LinkedList;
    
    public class Solution {
        public int[] findOrder(int numCourses, int[][] prerequisites) {
            int[] result = new int[numCourses];
            int k = 0;
            LinkedList<Integer> queue = new LinkedList<>();
            int[] indegree = new int[numCourses];
            for (int i = 0; i < prerequisites.length; i++) {
                indegree[prerequisites[i][0]]++;
            }
    
            for (int i = 0; i < numCourses; i++) {
                if(indegree[i] == 0){
                    queue.offer(i);
                }
            }
            
            int count = 0;
            while (!queue.isEmpty()){
                int course = queue.poll();
                result[k++] = course;
                count++;
                for (int i = 0; i < prerequisites.length; i++) {
                    if(prerequisites[i][1] == course){
                        indegree[prerequisites[i][0]]--;
                        if(indegree[prerequisites[i][0]] == 0){
                            queue.offer(prerequisites[i][0]);
                        }
                    }
                }
            }
            return count == numCourses ? result : new int[0];
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.