You is given an array x of n positive numbers. You start at point (0,0) and moves x[0] metres to the north, then x[1] metres to the west, x[2] metres to the south, X[3] metres to the east and so on. In the other words, after each move your direction changes counter-clockwise.
Write a one-pass algorithm with O (1) Extra space to determine, if your path crosses itself, or not.
Example 1:
Given x = [2112],┌───┐│ │└───┼──>Returntrue (self crossing)
Example 2:
Given x = [1234],┌──────┐│ │││└────────────>Returnfalse (notself crossing)
Example 3:
Given x = [1111],┌───┐│ │└───┼>Returntrue (self crossing)
Thinking of solving problems
The intersection can be divided into the following three cases:
- The fourth line intersects the first line
- Fifth line intersects or overlaps the first line
- The sixth line intersects the first line
Point Xi is the last point given.
Implementation code
//Runtime:1 MS Public class solution { Public Boolean isselfcrossing(int[] x) {intlen = x.length;if(Len <=3)return false; for(inti =3; i < Len; i++) {if(X[i] >= x[i-2] && x[i-1] <= x[i-3]) {return true; }if(I >=4) {if(x[i-1] = = x[i-3] && X[i] + x[i-4] >= x[i-2]) {return true; } }if(I >=5) {if(x[i-2]-x[i-4] >=0&& X[i] >= x[i-2]-x[i-4] && x[i-1] >= x[i-3]-x[i-5] && x[i-1] <= x[i-3]) {return true; } } }return false; }}
[Leetcode] Self Crossing