2ms java solution easy to read


  • -1
    public class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        int[] id = new int[numCourses];
        for (int i=0;i<numCourses;i++){
            id[i] = i;
        }
        for (int[] pair : prerequisites){
            id[pair[0]] = pair[1];
            int rootx = root(id,pair[0]);
            int rooty = root(id,pair[1]);
            if (rootx==-1 || rooty==-1) return false;
            
        }
        return true;
    }
    
    private int root(int[] id, int i){
        int count = 0;
        while (i != id[i]){
            i = id[i];
            count++;
            if (count==id.length) return -1;
        }
        return i;
    }
    

    }


  • 0
    C

    Try test case:
    "
    5
    [[1,0],[1,3],[0,1]]
    "
    this code give impossible result while the expected answer is false.

    this case is about one class having multiple pre-requisite and the later requirement overwrite the previous.

    The submission result is accepted,


  • 1
    Y

    Try this case:

    5
    [[0, 1], [1, 2], [1, 4], [3, 1], [2, 3]]

    Wrong answer


Log in to reply
 

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