[Leetcode] [JavaScript] Self Crossing

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.