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)
题意概述:
给定一个大小为n的正实数数组,代表一条路径,路径由向北,向西,向南,向东组成,判断这条路径是否自交,要求额外空间为O(1)
算法分析:
如果去除了题目要求的额外空间复杂度为O(1)的条件,这题就变得非常简单,解法也显而易见,只要记录下这条路径上所有的点就可判断是否自交,但是这样做是O(n)的。所以要对题目进行分析,既然题目要求让我们考虑是否自交,那么思考的入手点应定为如何定义自交,仔细思考下可以发现自交只分为以下三种情况,而无其他可能:
①涉及四条边的相交;
②涉及五条边的重合;
③涉及六条边的相交;
以下为三种相交图:
因此如果发生某一条边相交,它仅涉及当前边的前三到五条边,因此得出以下代码,算法复杂度为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; } }