lintcode(616)安排课程

来源:互联网 发布:日本扫码软件 编辑:程序博客网 时间:2024/06/06 00:03

Description:

你需要去上n门九章的课才能获得offer,这些课被标号为 0 到 n-1 。
有一些课程需要“前置课程”,比如如果你要上课程0,你需要先学课程1,我们用一个匹配来表示他们: [0,1]

给你课程的总数量和一些前置课程的需求,返回你为了学完所有课程所安排的学习顺序。

可能会有多个正确的顺序,你只要返回一种就可以了。如果不可能完成所有课程,返回一个空数组。

Sample:

给定 n = 2, prerequisites = [[1,0]]
返回 [0,1]

给定 n = 4, prerequisites = [1,0],[2,0],[3,1],[3,2]]
返回 [0,1,2,3] or [0,2,1,3]

Solution:

ArrayList<HashSet<Integer>>

If finish

Then finish (HashSet)

0

{1,2}

1

{3}

2

{3}

3

{}

Int[] numPre

course

Number of preRequireCoures

0

0

1

1

2

1

3

2

Go through the array prerequisites torecord the course and its followers (if we have finished a, then we can finishb. Push b to HashSet of a). Then record the number of previous required courses(PRC)of each course. If the number is zero, then push it to the sorted courses. Thenwe need to poll out the class and record it in the result, when  poll out one course, renew the number of PRC ofthe related course , then check whether it can be offer to the queue. Go againthe last operation until the sorted courses is empty.  

public class Solution {    /**     * @param numCourses a total of n courses     * @param prerequisites a list of prerequisite pairs     * @return the course order     */    public int[] findOrder(int numCourses, int[][] prerequisites) {        // Write your code here        ArrayList<HashSet<Integer>> record = new ArrayList<HashSet<Integer>>();        for(int i = 0;i<numCourses;i++){            record.add(new HashSet<Integer>());        }                for(int i = 0;i<prerequisites.length;i++){            record.get(prerequisites[i][1]).add(prerequisites[i][0]);        }                int[] numPre = new int[numCourses];        for(int i = 0;i<numCourses;i++){            for(int after : record.get(i)){                numPre[after]++;            }        }                Queue<Integer> sortCourse = new LinkedList<Integer>();        for(int i = 0;i<numCourses;i++){            if(numPre[i] == 0){                sortCourse.offer(i);            }        }        int[] result = new int[numCourses];        int count = 0;        while(!sortCourse.isEmpty()){            int current = sortCourse.poll();            for(int after : record.get(current)){                numPre[after]--;                if(numPre[after] == 0){                    sortCourse.offer(after);                }            }            result[count++] = current;        }        return count == numCourses ? result : new int[0];    }}


原创粉丝点击