题目
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)
分析:
根据题目,我们可以得知,当数组元素个数大于等于6时,i从0开始计数,大于等于5,判断前i次运动是否相交,不相交的情况只有下图中描述的三种情况。我们可以把每一种情况称为运动所处的状态。第一种状态,第i条边x[i]只可能与x[i-5]和x[i-3]相交(界面这两条边之间的边可以不考虑);第二种状态,x[i]只可能与x[i-3]相交;第三种状态是前者的综合,前半部分处在第一种状态,后半部分处在第二种状态,状态改变发生在x[i]小于x[i - 2] - x[i - 4]时,注意,只能是第一种状态变为第二种状态,第二种状态不能转变为第一种状态。知道每一次运动所处的状态是很重要的,因为我们可以根据所处状态判断当前边可能与谁相交,也可以根据当前状态判断状态会不会发生改变。i小于5,判断前i次运动是否相交,可以单独判断。
根据上面分析中的思路,我写出了如下的解题代码:
public class LeetCode1351 {
public boolean isSelfCrossing(int[] x) {
int len = x.length;
if (len < 4) {
return false;
}
// 判断前四个是否存在相交
if (len >= 4 && x[2] <= x[0] && x[3] >= x[1]) {
return true;
}
// 状态1. 往外转
// 状态2. 往里转
// 往外转能够在某一时刻转为往里转,但是往里转不能转为往外转
// 这是表明下次移动应该基于的状态
int stats = 1;
// 判断前5个是否存在相交
if (len >= 5) {
if (x[3] <= x[1]) {
stats = 2;
// 两种相交情况之一
if (x[3] == x[1] && x[4] >= x[2] - x[0]) {
return true;
// 两种相交情况之二
} else if(x[3] < x[1] && x[4] > x[2]){
return true;
}
}
// 判断是否改变状态
if (x[4] < x[2] - x[0]) {
stats = 2;
}
}
// 判断前i个是否存在相交
for(int i = 5; i < len; i++) {
// 所处的状态,决定了应该进行的判断
if (stats == 1) {
if (x[i - 1] <= x[i - 3]) {
// 两种相交情况之一
if (x[i - 1] >= x[i - 3] - x[i - 5] && x[i] >= x[i - 2] - x[i -4]) {
return true;
}
// 两种相交情况之二
if (x[i - 1] < x[i - 3] - x[i - 5] && x[i] >= x[i - 2]) {
return true;
}
// 判断是否改变状态
if (x[i] < x[i - 2] - x[i - 4]) {
stats = 2;
}
}
}
if (stats == 2) {
if (x[i] >= x[i - 2]) {
return true;
}
}
}
return false;
}
public static void main(String[] args) {
LeetCode1351 leetCode1351 = new LeetCode1351();
int[] x = new int[] {1,1,2,2,1,1};
System.out.println(leetCode1351.isSelfCrossing(x));
}
}
本文提供的解法思路清晰,但不是最优的,大家可以在此基础上优化。