Java Accepted simple solution


  • 0
    M
        public int[] findOrder(int numCourses, int[][] prerequisites) {
            Map<Integer, Set<Integer>> map = new HashMap<>();
            Map<Integer, Integer> degree = new HashMap<>();
            
            for(int i = 0; i < numCourses; i++) {
                degree.put(i, 0);
                map.put(i, new HashSet<Integer>());
            }
            
            for(int[] pre : prerequisites) {
                int after = pre[0];
                int before = pre[1];
                
                
                Set<Integer> set = map.get(before);
                if(!set.contains(after)) {
                    set.add(after);
                    degree.put(after, degree.get(after) + 1);
                }
                
                map.put(before, set);
            }
            
            Queue<Integer> queue = new LinkedList<Integer>();
            
            for(Integer course : degree.keySet()) {
                if(degree.get(course) == 0) {
                    queue.offer(course);
                }
            }
            
            int[] ret = new int[numCourses];
            int i = 0;
            while(!queue.isEmpty()) {
                int course = queue.poll();
                ret[i++] = course;
                if(map.containsKey(course)) {
                    for(int after: map.get(course)) {
                        degree.put(after, degree.get(after) - 1);
                        if(degree.get(after) == 0) {
                            queue.offer(after);
                        }
                    }
                }
            }
            return i == numCourses ? ret : new int[0];
        }
    

Log in to reply
 

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