Neat Java Solution 0ms


  • 0
    T
        //for each step i, it could crossing from inside(the line 3 steps before) or outside(the line 5 steps before)
        //whether it is crossing from inside depends on: 1) if this step starts from a point could crossing(e.g.x[i-1]<=x[i-3] ) 2) if this step is long enough to crossing(x[i]>=x[i-2])
        //whether it is crossing from outside depends on: 1) x[i-3]-x[i-1]<=x[i-5] && x[i-1]<=x[i-3]; 2) x[i-2]>=x[i-4]&&x[i]>=x[i-2]-x[i-4]
        //whenever x[i]==0, it's crossing
    public boolean isSelfCrossing(int[] x) {
        if(x.length<4){
            for(int step: x){
                if(step==0) return true;
            }
            return false;
        }
        for(int i=0;i<3;i++){
            if(x[i]==0) return true;//check whether first 3 are 0
        }
        //for i<4, it can only crossing from inside
        for(int i=3;i<4&&i<x.length;i++){
            if(x[i]==0) return true;
            if(x[i-1]<=x[i-3]&&x[i]>=x[i-2]) return true;
        }
        if(x.length>4){
            if(x[4]==0) return true;
            if(x[3]<x[0]&&x[4]>=x[2]) return true;
            if(x[3]==x[1]&&x[4]>=x[2]-x[0]) return true;
        }
        for(int i=5;i<x.length;i++){
            if(x[i]==0) return true;
            if(x[i-1]<=x[i-3]&&x[i]>=x[i-2]) return true;
            if(x[i-1]<=x[i-3]&&x[i-3]-x[i-1]<=x[i-5]&&x[i-2]>=x[i-4]&&x[i]>=x[i-2]-x[i-4]) return true;
        }
        return false;
        
    }

Log in to reply
 

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