zoukankan      html  css  js  c++  java
  • 刷题207. Course Schedule

    一、题目说明

    题目207. Course Schedule,给定n门课程,一些课程需要先修一些课程,判断能否修完所有课程。难度是Medium!

    二、我的解答

    这个题目是数据结构中的拓扑排序,通过栈可以实现。

    class Solution{
    	public:
    		bool canFinish(int numCourses, vector<vector<int>>& prerequisites){
    			if(prerequisites.size()<2) return true;
    			stack<int> st;
    			vector<int> count(numCourses,0);
    			unordered_map<int,vector<int>> ump;
    			 
    			for(int i=0;i<prerequisites.size();i++){
    				vector<int> tmp = prerequisites[i];
    				int x = tmp[0];
    				int y = tmp[1];
    				count[x]++;
    				ump[y].push_back(x);
    			}
    			//将所有入度为0的元素入栈 
    			for(int i=0;i<numCourses;i++){
    				if(count[i]<1){
    					st.push(i);
    				} 
    			}
    			while(! st.empty()){
    				int x = st.top();
    				st.pop();
    				if(ump.count(x)>0){
    					vector<int> tmp = ump[x];
    					for(int j=0;j<tmp.size();j++){
    						int y = tmp[j];
    						count[y]--;
    						if(count[y]<1){
    							st.push(y);
    						}
    					}
    				}
    			}
    			int finish = 0;
    			for(int i=0;i<numCourses;i++){
    				if(count[i]<1){
    					finish++;
    				} 
    			}
    			if(finish==numCourses) return true;
    			else return false;
    		}
    };
    

    性能如下:

    Runtime: 20 ms, faster than 87.86% of C++ online submissions for Course Schedule.
    Memory Usage: 14.6 MB, less than 40.00% of C++ online submissions for Course Schedule.
    

    三、优化措施

    所有文章,坚持原创。如有转载,敬请标注出处。
  • 相关阅读:
    cors解决跨域
    神经网络和keras
    tensorflow笔记
    5.聚类算法-kmeans
    4.回归类算法-目标值连续型
    3.分类算法-目标值离散型
    Phaser.js开发小游戏之洋葱头摘星星
    VS Code 插件之 vscode-debug-visualizer
    Phaser.js开发小游戏之Phaser.js介绍
    微信小程序中写threejs系列之 threejs-miniprogram
  • 原文地址:https://www.cnblogs.com/siweihz/p/12286158.html
Copyright © 2011-2022 走看看