一个算法题--Self Crossing

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:

Example3:

Answer:
 1 public boolean isSelfCrossing(int[] x) {
 2         if(x==null||x.length<=3){
 3             return false;
 4         }
 5         for(int i=3;i<x.length;i++){
 6             if(x[i]>=x[i-2]&&x[i-1]<=x[i-3]){  // case 1
 7                 return true;
 8             }else if(i>=4&&x[i-1]==x[i-3]&&x[i]+x[i-4]>=x[i-2]){  // case 2
 9                     return true;
10             }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
11                 return true;
12             }
13         }
14         return false;
15     }

 

posted on 2016-03-02 15:09  Yanspecial  阅读(307)  评论(0编辑  收藏  举报