lintcode(616)安排课程

本文介绍了一种用于解决课程学习顺序问题的算法。该算法基于图的拓扑排序思想,通过记录每门课程及其前置课程的关系,实现自动规划学习路径。适用于需要解决依赖关系排序的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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];
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值