LC.P335[路径交叉]

方法一:找规律

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public boolean isSelfCrossing(int[] distance) {
int n = distance.length;
if (n < 4) return false;
for (int i = 3; i < n; ++i) {
if (distance[i] >= distance[i - 2] && distance[i - 1] <= distance[i - 3]) return true;
if (i >= 4 && distance[i - 1] == distance[i - 3] && distance[i] + distance[i - 4] >= distance[i - 2])
return true;
if (i >= 5 && distance[i - 1] <= distance[i - 3] && distance[i - 2] > distance[i - 4] && distance[i] + distance[i - 4] >= distance[i - 2] && distance[i - 1] + distance[i - 5] >= distance[i - 3])
return true;
}
return false;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$