Middle-题目118:210. Course Schedule II

来源:互联网 发布:上海财经大学 网络教育 编辑:程序博客网 时间:2024/05/17 21:48

题目原文:
There are a total of n courses you have to take, labeled from 0 to n - 1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.
题目大意:
在Middle-题目86的基础上,求修课的序列。如果不可能修完所有课程,返回一个空序列。
题目分析:
跟上一题差不多,这次是求拓扑序列,但返回值有点奇怪,不知道empty array为什么有时候指的是new int[1]有时候又是new int[0]
源码:(language:java)

public class Solution {    public int[] findOrder(int numCourses, int[][] prerequisites) {        if(numCourses==1)            return new int[1];        Map<Integer, Set<Integer>> adjList = new HashMap<Integer,Set<Integer>>();        int[] indegree = new int[numCourses];        for(int i = 0; i<numCourses;i++)            adjList.put(i, new HashSet<Integer>());        for(int[] edge : prerequisites) {            if(!adjList.get(edge[1]).contains(edge[0])) {                adjList.get(edge[1]).add(edge[0]);                indegree[edge[0]]++;            }        }        int[] order = new int[numCourses];        int i=0;        int topoVertical = findZeroIndegree(indegree);        while(topoVertical!=-1) {                       indegree[topoVertical] = -1;            for(Integer vertical : adjList.get(topoVertical)) {                if(indegree[vertical]!=-1)                    indegree[vertical]--;            }            adjList.remove(topoVertical);            order[i++]=topoVertical;            topoVertical = findZeroIndegree(indegree);        }        if(i==numCourses)            return order;        else            return new int[0];    }    private int findZeroIndegree(int[] indegree) {        for(int i = 0;i<indegree.length;i++)            if(indegree[i]==0) {                return i;            }        return -1;    }}

成绩:
37ms,beats 21.31%,众数10ms,8.81%
Cmershen的碎碎念:
这道题我觉得oj的判题怪怪的,因为一直提示Special judge: No expected output available. 不知道为什么要返回new int[1]而不是new int[0]或null。所以此题的ac率超低,但难度应该跟前一题是一样的。

0 0
原创粉丝点击