算法题目
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.
算法分析
这一题有O(1)的空间复杂度限制,所以不能额外开多数组来储存坐标信息,我一开始是想没加入一个顶点从重新计算前面的顶点看有没有交叉,但这样的时间复杂度是O(N^2),虽然题目没有要求时间复杂度,但是觉得这样过于暴力不优雅,应该也不是最优的解法。然后我尝试着把集中自交情况画出来,发现自交的只有三种情况。
按照这三个分类我们不难写出程序
bool isSelfCrossing(vector<int>& x) {
for(int i = 0 ; i < x.size() ; i++){
if(i>=3&&x[i]>=x[i-2]&&x[i-1]<=x[i-3])
return true;
if(i>=4&&x[i-1]==x[i-3]&&x[i]+x[i-4]==x[i-2])
return true;
if(i>=5&&x[i-1]<x[i-3]&&x[i-1]>=x[i-3]-x[i-5]&&x[i-3]>=x[i-5]&&x[i]>=x[i-2]-x[i-4]&&x[i-2]>=x[i-4])
return true;
}
return false;
}