刷题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.

三、优化措施

猜你喜欢

转载自www.cnblogs.com/siweihz/p/12286158.html