[LeetCode][JavaScript]Self Crossing
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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 };
以上是关于[LeetCode][JavaScript]Self Crossing的主要内容,如果未能解决你的问题,请参考以下文章
jquery问题,怎样让选择器获取通过变量获取相应的id:例如,我想让jquery获取#sel01,#sel02,#sel03