Java for LeetCode 207 Course Schedule【Medium】
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, is it possible for you to finish all courses?
For example:
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.
2, [[1,0],[0,1]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
解题思路一:
把每个节点放到图里,然后对每个节点进行BFS,如果出现自环,则为false,否则返回true,JAVA实现如下:
static public boolean canFinish(int numCourses, int[][] prerequisites) {
if (prerequisites.length == 0 || prerequisites[0].length == 0)
return true;
HashMap<Integer, UndirectedGraphNode> hm = new HashMap<Integer, UndirectedGraphNode>();
for (int[] nums : prerequisites)
for (int i = 0; i < nums.length - 1; i++) {
if (!hm.containsKey(nums[i]))
hm.put(nums[i], new UndirectedGraphNode(nums[i]));
if (!hm.containsKey(nums[i + 1]))
hm.put(nums[i + 1], new UndirectedGraphNode(nums[i + 1]));
hm.get(nums[i]).neighbors.add(hm.get(nums[i + 1]));
}
Iterator<Integer> iterator = hm.keySet().iterator();
while (iterator.hasNext())
if (haveLoop(hm.get(iterator.next())))
return false;
return true;
} static boolean haveLoop(UndirectedGraphNode root) {
HashMap<UndirectedGraphNode, Boolean> hm = new HashMap<UndirectedGraphNode, Boolean>();
Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
hm.put(root, true);
queue.add(root);
while (!queue.isEmpty()) {
UndirectedGraphNode temp = queue.poll();
for (UndirectedGraphNode temp2 : temp.neighbors) {
if (temp2 == root)
return true;
if (!hm.containsKey(temp2)) {
hm.put(temp2, true);
queue.add(temp2);
}
}
}
return false;
}
结果TLE,问题在于判断有向图是否有环的时候,对每一个节点判断其实浪费了很多时间%>_<%
解题思路二:
实际上,本题应该用拓扑排序判断图中是否有环,在储存边的时候,应该用set进行储存,具体内存请看考这篇博客:【LeetCode】Course Schedule 解题报告
JAVA传送门如下:
public boolean canFinish(int numCourses, int[][] prerequisites) {
List<Set> posts = new ArrayList<Set>();
for (int i = 0; i < numCourses; i++)
posts.add(new HashSet<Integer>());
for (int i = 0; i < prerequisites.length; i++)
posts.get(prerequisites[i][1]).add(prerequisites[i][0]); // count the pre-courses
int[] preNums = new int[numCourses];
for (int i = 0; i < numCourses; i++) {
Set set = posts.get(i);
Iterator<Integer> it = set.iterator();
while (it.hasNext()) {
preNums[it.next()]++;
}
} // remove a non-pre course each time
for (int i = 0; i < numCourses; i++) {
// find a non-pre course
int j = 0;
for ( ; j < numCourses; j++) {
if (preNums[j] == 0) break;
} // if not find a non-pre course
if (j == numCourses) return false; preNums[j] = -1; // decrease courses that post the course
Set set = posts.get(j);
Iterator<Integer> it = set.iterator();
while (it.hasNext()) {
preNums[it.next()]--;
}
} return true;
}
Java for LeetCode 207 Course Schedule【Medium】的更多相关文章
- Java for LeetCode 146 LRU Cache 【HARD】
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...
- Java for LeetCode 072 Edit Distance【HARD】
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2 ...
- Java for LeetCode 115 Distinct Subsequences【HARD】
Given a string S and a string T, count the number of distinct subsequences of T in S. A subsequence ...
- Java for LeetCode 097 Interleaving String 【HARD】
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example, Given: s1 ...
- LeetCode 31. Next Permutation【Medium】
Implement next permutation, which rearranges numbers into the lexicographically next greater permuta ...
- Java for LeetCode 210 Course Schedule II
There are a total of n courses you have to take, labeled from 0 to n - 1. Some courses may have prer ...
- LeetCode:课程表II【210】
LeetCode:课程表II[210] 题目描述 现在你总共有 n 门课需要选,记为 0 到 n-1. 在选修某些课程之前需要一些先修课程. 例如,想要学习课程 0 ,你需要先完成课程 1 ,我们用一 ...
- LeetCode:累加数【306】
LeetCode:累加数[306] 题目描述 累加数是一个字符串,组成它的数字可以形成累加序列. 一个有效的累加序列必须至少包含 3 个数.除了最开始的两个数以外,字符串中的其他数都等于它之前两个数相 ...
- LeetCode:二进制手表【401】
LeetCode:二进制手表[401] 题目描述 二进制手表顶部有 4 个 LED 代表小时(0-11),底部的 6 个 LED 代表分钟(0-59). 每个 LED 代表一个 0 或 1,最低位在右 ...
随机推荐
- rehat 出现GDB debuginfo-install 问题处理
本人使用rhel 6 GDB 调试代码时,出现以下错误: Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.166 ...
- 在linux下运行apt-get update 时,报错/var/lib/apt/lists/lock
在运行apt-get update 时,报下面的错误: E: 无法获得锁 /var/lib/apt/lists/lock - open (11: Resource temporarily unavai ...
- Linux服务器管理: 系统的定时任务crond
cornd 是定时任务的守护进程 这个服务系统是默认启动的 [root@localhost/]#/etc/init.d/crond strat|restart|stop [root@localhos ...
- InnerClass内部类
1,内部类概述 定义:把A类定义在B类内部,则A类是内部类.如下所示: class Outer1{外部类 String name1; public void show(){ System.out.pr ...
- Outlook不能打开附件(提示:无法创建文件xx,请右键单击要在其中创建文件的文件夹..)
问题分析: 出现这种问题的几率很小,除非你是每天都需要使用Outlook的办公人员.出现这种问题我想有如下两种可能.1.注册表中指定的附档临时保存的目录没有写入的相关权限.2.同名附档已存在且权限出现 ...
- AlwaysOn可用性组测试环境安装与配置(二)--AlwaysOn配置(界面与T-SQL)
四.AlwaysOn配置 1.开启AlwaysOn高可用性功能. 1.1.开启Server01的可用性组 1.2.需要重启服务:属于SQL server群集节点的服务,需要通过故障转移界面重启 1.3 ...
- OS X 10.10.5编译Android5.1.1源码
--------------------------------------------------写在前面---------------------------------------------- ...
- 【python网络编程】使用rsa加密算法模块模拟登录新浪微博
一.基础知识 http://blog.csdn.net/pi9nc/article/details/9734437 二.模拟登录 因为上学期参加了一个大数据比赛,需要抓取数据,所以就想着写个爬虫抓取新 ...
- Maven生命周期和插件机制
Maven中的一个非常重要的概念是生命周期和插件,这篇文章重点介绍下Maven的生命周期. Maven的生命周期是抽象的,具体的功能是有具体的插件来完成的,Maven有相当多的功能插件,以至于Mave ...
- java文档
http://www.boyunjian.com/javadoc/com.dyuproject.protostuff/protostuff-me/1.0.5/_/com/dyuproject/prot ...