You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
varcheckIfPrerequisite=function(n,prerequisites,queries){// from to map collectionconstmap=prerequisites.reduce((m,e)=>{if(!m[e])m[e]=[];m[e]=[...m[e], ...prerequisites.filter(query=>query[0]==e[1])]returnm;},{})// console.log(map)returnqueries.map(([from,to])=>{conststack=prerequisites.filter(pre=>pre[0]==from)constseen=newSet()while(stack.length>0){// console.log('stack1', stack)constcurr=stack.shift()if(curr[1]==to){returntrue}for(lettargetofmap[curr]){if(target[1]==to){returntrue}if(seen.has(target))continueseen.add(target)stack.push(target)}}returnfalse})};
Runtime: 1020 ms, faster than 24.19% of JavaScript online submissions for Course Schedule IV.
Memory Usage: 78.6 MB, less than 6.45% of JavaScript online submissions for Course Schedule IV.
/** * @param {number} n * @param {number[][]} prerequisites * @param {number[][]} queries * @return {boolean[]} */varcheckIfPrerequisite=function(n,prerequisites,queries){// this way to generate a mapconstmap=[...Array(n)].map(()=>[]);for(let[pre,next]ofprerequisites){map[pre].push(next);}returnqueries.map(([from,to])=>{conststack=[from]constseen=newSet()// 此处依旧是 bfswhile(stack.length>0){constcurr=stack.shift()for(lettargetofmap[curr]){// 查询到map对应的 数组关系if(target==to){// 如果查询到了 对应的值, 抛出.returntrue}if(seen.has(target))continue// 此处缓存已经走过的路, 防止无限循环查询seen.add(target)stack.push(target)}}returnfalse})};
The text was updated successfully, but these errors were encountered:
https://leetcode.com/problems/course-schedule-iv/
题目意思是给定三个输入参数
n, prerequisites, queries
我的第一版答案, 可以解决上面的问题. 但是运行超时了. 输入参数
解决思路
我一开始是试试,广度优先, 换成深度优先. 但是没有什么卵用,
用双向链表, 但是没写出来. bug一大堆. 况且据我所知, 双向链表属于锦上添花, 没啥用.
空间换时间, 在循环外面生成一张查询表, 于是有了下面的答案, 有一定效果. 但是我的查询表不够高效, 我的是 map -> [数组]->[数组].
经过以上优化后的代码如下, 之前n只能是72, 现在n能跑到100了, 这说明这个思路是对的.
这个时候大脑已经崩了. 直接翻答案.
经过进一步优化,终于解决了这个问题. 原来我上面的查询关系表太low了, 真正的高效查询表是一个图
举个例子
[[0,1],[1,2],[2,3],[3,4]]
应该生成如下图[4,3],[4,1],[4,0],[3,2],[3,1],[3,0],[2,1],[2,0],[1,0]
对应的图应该是.. 我就不画了, 没绘画天赋...而图的最佳表示方式就是map. 而map的查询速度是非常高效的. 而如果有了这样的抽象思维, 问题自然迎刃而解, 其实就是图的搜索.
最终答案
The text was updated successfully, but these errors were encountered: