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,最低位在右 ...
随机推荐
- 【8-23】node.js学习笔记
Node入门 //请求(require)Node.js自带的 http 模块,并且把它赋值给 http 变量 //变成了一个拥有所有 http 模块所提供的公共方法的对象 var http = req ...
- R语言练习(一)
b = seq(from=0, to=1, by=0.001) #一次方 l1 = function(b){ b^1 } y1 = l1(b) #二次方 l2 = function(b){ b^2 } ...
- winServer2003除默认端口外的其他端口只能本地访问,关闭防火墙即可
winServer2003除默认端口外的其他端口只能本地访问,关闭防火墙即可
- java 在接口里函数不能重载?
项目里使用hession远程调用serviceRemote接口,而serviceRemote接口里有两个save方法,参数分别是CpCredential对象和List,但运行发现会报莫名其妙的错. 后 ...
- JSON格式转换(javascript)
使用ajax从后台抓取数据后,如果有多个值,可以使用json传值. ajax例子如下,在返回的类型里面,可以是文本型(text),JSON格式(json),超文本类型(html),XML文件类型(xm ...
- 01Getting Started---Getting Started with ASP.NET Web API 2入门WebApi2
HTTP 不只是为了生成 web 页面.它也是建立公开服务和数据的 Api 的强大平台.HTTP 是简单的. 灵活的和无处不在.你能想到的几乎任何平台有 HTTP 库,因此,HTTP 服务可以达到范围 ...
- 《Lua程序设计 第二版》学习笔记一
Lua简介 Lua是一种简单.可拓展.可移植及高效的脚本语言. 开始 Lua之间不需要分隔符 运行方式: Linux下: lua -i prog dofile("lib1.lua" ...
- DAY5 php + mysql 写一个简单的sql注入平台
php mysql 在浏览器输入用户名,去数据库查询.查到则显示在浏览器,查不到则显示空. sql 里面三个字段 id username password create table t1 (id in ...
- transition代替简单的animation注意事项
一. transition 和 animation 不支持 Internet Explorer 9,以及更早的版本. 二. 要变化的属性 transition-property:要变化的属性, ...
- 9 patch png 的上下左右
9 patch png 的上下左右 前言: 9 patch png 图片,扩展名为.9.png,是一个标准的PNG图像,它包括额外的1个像素的边界,通过对这个边界的描述来达到我们预期的拉伸效果.a ...