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.json
Example 1:數組
Given x = ,
?????
? ?
???????>
?
Return true (self crossing)[2, 1, 1, 2]
Example 2:spa
Given x = ,
????????
? ?
?
?
?????????????>
Return false (not self crossing)
[1, 2, 3, 4]
Example 3:code
Given x = ,
?????
? ?
?????>
Return true (self crossing)[1, 1, 1, 1]
題意概述:blog
給定一個大小爲n的正實數數組,表明一條路徑,路徑由向北,向西,向南,向東組成,判斷這條路徑是否自交,要求額外空間爲O(1)it
算法分析:io
若是去除了題目要求的額外空間複雜度爲O(1)的條件,這題就變得很是簡單,解法也顯而易見,只要記錄下這條路徑上全部的點就可判斷是否自交,可是這樣作是O(n)的。因此要對題目進行分析,既然題目要求讓咱們考慮是否自交,那麼思考的入手點應定爲如何定義自交,仔細思考下能夠發現自交只分爲如下三種狀況,而無其餘可能:ast
①涉及四條邊的相交;class
②涉及五條邊的重合;
③涉及六條邊的相交;
如下爲三種相交圖:
所以若是發生某一條邊相交,它僅涉及當前邊的前三到五條邊,所以得出如下代碼,算法複雜度爲O(n),額外空間複雜度爲O(1):
class Solution { public boolean isSelfCrossing(int[] x) { int length = x.length; for(int i=3;i<length;i++){ if(x[i]-x[i-2]>=0&&x[i-1]-x[i-3]<=0){ return true; } if(i>=4&&x[i-1]==x[i-3]&&x[i-2]>=x[i-4]&&x[i]>=x[i-2]-x[i-4]){ return true; } if(i>=5&&x[i-2]>=x[i-4]&&x[i-3]>=x[i-5]&&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; } }