Self Crossing
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, metres to the east and so on. In the other words, after each move your direction changes counter-clockwise.
Write a one-pass algorithm O(1)
with extra space to determine, if your path crosses itself, or not.
Example 1:
x [2, 1, 1, 2]
, Return true (self crossing)
Example 2:
x [1, 2, 3, 4]
, Return false (not self crossing)
Example 3:
x [1, 1, 1, 1]
, Return true (self crossing)
https://leetcode.com/problems/self-crossing/
Draw the line counterclockwise to find out if the line has a cross.
See figure, three cases, corresponding to the comments in the code.
1 /**2 * @param {number[]} x3 * @return {Boolean}4 */5 varIsselfcrossing =function(x) {6 for(vari = 3; i < x.length; i++){7 //I. [2, 1, 1, 2]8 if(X[i-3] && x[i] >= x[i-2] && x[i-1] <= x[i-3]) 9 return true;Ten //Ii. [1, 1, 2, 1, 1] One if(X[i-4] && x[i-3] = = = X[i-1] && x[i-4] + x[i] >= x[i-2]) A return true; - //Iii. [1, 1, 2, 2, 1, 1] - if(X[i-5] && x[i-4] <= x[i-2] && x[i] + x[i-4] >= x[i-2] the&& x[i-3] >= x[i-1] && x[i-5] + x[i-1] >= x[i-3]) - return true; - } - return false; +};
[Leetcode] [JavaScript] Self Crossing