Course Schedule II java 走地牙 CTCI 4.7 变形

类似4.7 需要变化一下形式 4.7中课程不是数字 先构造graph 然后在操作现在看起来有点麻烦 以后再实现

/*
想写一个通用一点的 因为course不一定是数字 所以建立两个map 一个用于储存课程 与他需要的前置课程数量,另一个储存课程 与他后置的课程list
    这样 利用bfs 每次把当前课程后置list的课程找出来 将前置课程已经为0的课程放置到queue里面 最终可以找出上课的顺序;
*/
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) {
        if(numCourses == 0) return new int[]{};
        Map<Integer, ArrayList<Integer>> postMap = new HashMap<>();
        Map<Integer, Integer> prepMap = new HashMap<>();
        int[] result = new int[numCourses];
        for(int i = 0; i < numCourses; i++) {
            postMap.put(i, new ArrayList<Integer>());
            prepMap.put(i, 0);
        }
        for(int i = 0; i < prerequisites.length; i++) {
            prepMap.put(prerequisites[i][0],prepMap.get(prerequisites[i][0]) + 1);
        }
        for(int i = 0; i < prerequisites.length; i++) {
            postMap.get(prerequisites[i][1]).add(prerequisites[i][0]);
        }
        Queue<Integer> q = new LinkedList<>();
        for(int i = 0; i < numCourses; i++) {
            if(prepMap.get(i) == 0) {
                q.offer(i);
            }
        }
        int count = 0;
        while(!q.isEmpty()){
            int temp = q.poll();
            result[count++] = temp;
            for(Integer i : postMap.get(temp)) {
                prepMap.put(i, prepMap.get(i) - 1);
                if(prepMap.get(i) == 0) {
                    q.offer(i);
                }
            }
        }
        if(count == numCourses) {
            return result;
        }
        return new int[]{};
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值