my solution with map in java


  • 0
    W

    ...
    class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
    if(prerequisites == null) return true ;
    Map<Integer,Integer> map = new HashMap<>();
    for(int i =0 ;i < prerequisites.length;i++){
    if(!map.containsKey(prerequisites[i][1]))
    map.put(prerequisites[i][0],prerequisites[i][1]);
    else{
    int k = map.get(prerequisites[i][1]);
    while(map.containsKey(k)){
    if(k == prerequisites[i][0])
    return false;
    k = map.get(k);
    }
    if( k == prerequisites[i][0]){
    return false;
    }
    map.put(prerequisites[i][0],prerequisites[i][1]) ;
    }
    }
    return true;
    }
    }
    ...


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.