zoukankan      html  css  js  c++  java
  • [LeetCode][JavaScript]Self Crossing

    Self Crossing

    You are 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 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 = [2, 1, 1, 2],
    Return true (self crossing)
    

    Example 2:

    Given x = [1, 2, 3, 4],
    Return false (not self crossing)
    

    Example 3:

    Given x = [1, 1, 1, 1],
    Return true (self crossing)

    https://leetcode.com/problems/self-crossing/


    逆时针画线,求线是否有交叉。

    看图,三种情况,对应了代码中的注释。

      

     1 /**
     2  * @param {number[]} x
     3  * @return {boolean}
     4  */
     5 var isSelfCrossing = function(x) {
     6     for(var i = 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;
    10         //ii. [1, 1, 2, 1, 1]
    11         if(x[i - 4] && x[i - 3] === x[i - 1] && x[i - 4] + x[i] >= x[i - 2]) 
    12             return true;
    13         //iii. [1, 1, 2, 2, 1, 1]
    14         if(x[i - 5] && x[i - 4] <= x[i -2] && x[i] + x[i - 4] >= x[i -2] 
    15             && x[i - 3] >= x[i - 1] && x[i - 5] + x[i - 1] >= x[ i - 3]) 
    16             return true;
    17     }
    18     return false;
    19 };
  • 相关阅读:
    java
    MVC4重复提交数据
    cache
    Nosql
    MVC4重复提交
    PHP Java
    .net performance
    How the Runtime Locates Assemblies
    android
    window.onscroll
  • 原文地址:https://www.cnblogs.com/Liok3187/p/5218788.html
Copyright © 2011-2022 走看看