Simple Java solution


  • 0
    A

    We look at any line x[i] and look at all possible scenarios under which one or another line will cross it. Any given line x[i] can only be crossed by x[i+3], x[i+4], or, x[i+5]. Even x[i+6] can cross x[i] but it can only be at the interface of x[i] and x[i+1], and that condition can as well be detected when we consider the same 3 conditions for x[i+1]. So we just need to write out the conditions under which each of x[i+3], x[i+4], or, x[i+5] cross x[i].

    public boolean isSelfCrossing(int[] x) {
            for(int i = 0; i < x.length; i++) {
                if(x.length <= i+3)
                    return false;
                if(x[i+3] >= x[i+1] && x[i+2] <= x[i])
                    return true;
    
                if(x.length <= i+4)
                    return false;
                if(x[i+3] == x[i+1] && x[i+4] == x[i+2] - x[i])
                    return true;
    
                if(x.length <= i+5)
                    return false;
                if(x[i+3] > x[i+1] && x[i+5] >= x[i+3] - x[i+1] && x[i+4] >= x[i+2] - x[i] && x[i+4] <= x[i+2])
                    return true;
            }
            return false;
        }
    

Log in to reply
 

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