问题描述:
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 moveyour direction changes counter-clockwise. Write a one-pass algorithm with O(1)
extra space to determine,if your path crosses itself, or not.
考虑所有可能否成Self Crossing的情况,共有三种情况:由4条边构成,由5条边构成,由6条边构成,如下图所示:
由于方向是逆时针90度变化的,所以构成self crossing的边是连续的,所以只需要遍历数组,考虑连续4条边 或5条边,或6条边能否封闭。
(2)写出各自的判别条件:
a) x[0]>=x[2]&&x[3]>=x[1];
b) x[1]==x[3]&&x[0]+x[4]>=x[2];
c) x[1]<x[3]&&x[4]<x[2]&&x[0]+x[4]>=x[2];
在循环时,将变量i加入到每一个索引中;
(3)完成代码
Java语言实现
public class Solution {
public boolean isSelfCrossing(int[] x) {
if(x.length<4){
return false;
}
int[] tmp=new int[4];
for(int i=0;i<x.length-3;i++){
if(x[i+1]>x[i+3]){
continue;
}
if(x[i+1]==x[i+3]){
if(x[i+2]<=x[i]){
return true;
// continue;
}
if(i+4<x.length&&x[i+0]+x[i+4]>=x[i+2]){
System.out.println(i+"6");
return true;
}
continue;
}
if(x[i]>=x[i+2]){
System.out.println(i+"4");
return true;
}
if(i<x.length-5){
if(x[i+0]+x[i+4]>=x[i+2]&&x[i+1]+x[i+5]>=x[i+3]&&x[i+4]<=x[i+2]){
System.out.println(i+"5");
return true;
}
}
}
return false;
}
}