您的位置:首页 > 其它

一个算法题--Self Crossing

2016-03-02 15:09 232 查看
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.

Example1:





Example2:





[b]Example3:[/b]

[b]

[/b]

Answer:


public boolean isSelfCrossing(int[] x) {
if(x==null||x.length<=3){
return false;
}
for(int i=3;i<x.length;i++){
if(x[i]>=x[i-2]&&x[i-1]<=x[i-3]){  // case 1
return true;
}else if(i>=4&&x[i-1]==x[i-3]&&x[i]+x[i-4]>=x[i-2]){  // case 2
return true;
}else if(i>=5&&x[i-2]>x[i-4]&&x[i]+x[i-4]>=x[i-2]&&x[i-1]<x[i-3]&&x[i-1]+x[i-5]>=x[i-3]){  //case 3
return true;
}
}
return false;
}






                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: