有三种情况:螺旋扩大 螺旋缩小 先螺旋扩大再螺旋缩小
下面是第三种情况的示意图:
+------------+
+---------+ | |
| | | |
| | | |
| | | |
| i-4 <----+ | |
i-2 | | | | +
| | | |
| |i |
| | | <---------------+
| | | |
+---------+-------+ | |
^ | |
| +-------------------------+
|
x[i] + x[i-4] >= x[i-2] x[i] + x[i-4] < x[i-2]
Then, possible early collision, nothing has to be changed
pretend we have started from
the plus sign point
class Solution
{
public:
bool isSelfCrossing(vector<int>& x)
{
x.insert(x.begin(), 4, 0);
int len = x.size();
int i = 4;
// outer spiral
for (; i < len && x[i] > x[i - 2]; i++);
if (i == len) return false;
// check border
if (x[i] >= x[i - 2] - x[i - 4])
{
x[i - 1] -= x[i - 3];
}
// inner spiral
for (i++; i < len && x[i] < x[i - 2]; i++);
return i != len;
}
};