题目描述
分析
不相交有以下三种情况
- 一直向外卷,此时只需要判定
dist[i]>dist[i-1]; - 一直向内卷,此时只需要判定
dist[i]<dist[i-1]; - 外卷转内卷,此时就需要在外卷和内卷之间做一个切分。即
dist[i]>dist[i-2]-dist[i-4];
答案
class Solution {public:bool isSelfCrossing(vector<int>& distance) {int n = distance.size();if (n < 4) return false;int i = 2;// 一直向外卷while (i < n && distance[i] > distance[i - 2]) i++;// 如果走完了,直接就可以返回不相交if (i == n) return false;// 如果向外卷转成了向内卷,i-1的长度减i-3的长度if (distance[i] >= distance[i - 2] - (i < 4 ? 0 : distance[i - 4])) {distance[i - 1] -= i < 3 ? 0 : distance[i - 3];}// 一直向内卷,注意i先加1,这样正好跟i-1的位置相比较,相当于内卷从i-1的位置开始的for (++i; i < n && distance[i] < distance[i - 2]; i++);// 如果 i 能走完就不会相交,相反,走不完就相交了return i != n;}};
