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,最低位在右 ...
随机推荐
- realloc,malloc,calloc函数的区别
from:http://www.cnblogs.com/BlueTzar/articles/1136549.html realloc,malloc,calloc的区别 三个函数的申明分别是: void ...
- svn搬移到gitlab及使用
svn是一款非常简便,易用的源代码管理工具,用了这么多年,对它情有独钟.都说习惯最难改,那为何要搬移到gitlab上呢? 喜欢尝试新东西,前提还是git比较强大,svn有的它都有,svn没有的它也有. ...
- ggplo2学习笔记——基本图形类型
1.散点图:又称散点分布图,是以一个变量为恨坐标,另一个变量为纵坐标,利用散点(坐标点)的分布形态反映变量统计关系的一种图形.可以用来确认两个变量之间的关系.绘制自由曲线.矩阵关联分析等. 2.条形图 ...
- box-sizing属性
我们都知道,设置元素的padding或者margin属性时都会改变元素的width和height,传统的方法是将padding和margin的值考虑进去,运用数学的方法进行计算来加以调整,以便使布局不 ...
- PHP函数 rtrim() 的一个怪异现象
今天用rtrim()函数时遇到了一个奇怪的问题: echo rtrim('<p></div>', '</div>'); // 输出为 <p echo ltri ...
- MFC线程内获取主窗口句柄
CWnd* h_q = AfxGetApp()->GetMainWnd(); //获取主窗口的句柄
- js搜索框输入提示(高效-ys8)
<style type="text/css"> .inputbox .seleDiv { border: 1px solid #CCCCCC; display: non ...
- iOS开发——多线程篇——快速生成沙盒目录的路径,多图片下载的原理、SDWebImage框架的简单介绍
一.快速生成沙盒目录的路径 沙盒目录的各个文件夹功能 - Documents - 需要保存由"应用程序本身"产生的文件或者数据,例如:游戏进度.涂鸦软件的绘图 - 目录中的文件会被 ...
- [POJ3096]Surprising Strings
[POJ3096]Surprising Strings 试题描述 The D-pairs of a string of letters are the ordered pairs of letters ...
- Unity调用Android方法
步骤 废话不多说,直接来步骤吧1.创建工程,弄大概像这样一个界面2.在unity中写好代码,像这样,记得给界面绑定好事件啥的 using UnityEngine; using UnityEngine. ...