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)
这道题是判断线段是否有交叉,题目难度为Medium。
三个点以下的情况不会出现交叉,从四个点开始分析。
画到第四个点(i=3)时交叉的情况只有下面一种情况,其他的情况不会出现交叉。循环遍历所有的点即可排除这种交叉的情况。
画到第五个点(i=4)时交叉的情况只有下面两种情况,其他情况不会出现交叉。原谅我粗糙的画图水平。。其中第一种情况和i=3时是相同的,在上面的判断中已经排除。循环遍历所有的点即可排除第二种交叉的情况。
画到第六个点(i=5)时交叉的情况只有下面三种情况,其他情况不会出现交叉。其中第一种情况和i=3时相同,第二种情况和i=4时相同,在之前的判断中已经排除。循环遍历所有的点即可排除第三种交叉的情况。
再后面点的情况和上面三种情况是相同的。因为当前线段不会和它之前的两个线段相交,逐个考虑和其他线段相交的情况就能够看出相交情况只有上面三种,以上三次遍历已经全部照顾到了。具体代码:
class Solution {
public:
bool isSelfCrossing(vector<int>& x) {
int sz = x.size();
for(int i=3; i<sz; ++i) {
if(x[i-1]<=x[i-3] && x[i]>=x[i-2])
return true;
}
for(int i=4; i<sz; ++i) {
if(x[i-1]==x[i-3] && x[i]+x[i-4]>=x[i-2])
return true;
}
for(int i=5; i<sz; ++i) {
if(x[i-2]>x[i-4] && x[i-1]<x[i-3] && x[i-1]+x[i-5]>=x[i-3] && x[i]+x[i-4]>=x[i-2])
return true;
}
return false;
}
};