一个算法题--Self Crossing
2016-03-02 15:09
232 查看
You are given an array x of
Write a one-pass algorithm with
Example1:
Example2:
[b]Example3:[/b]
[b]
[/b]
npositive 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; }
相关文章推荐
- SQL表连接查询inner join left join right join full join ...
- MapReduce
- iio adc转换应用编写
- 设计模式之代理模式
- JVM调优总结
- Qt安装与新建项目
- lua 与C通过c api传递table (2)
- 升级centos的内核到3.17版本
- win10设置自动更新
- bzoj1020 安全的航线flight
- Maven--Archetype
- TEMU:动态分析组件
- HTML4 和 HTML5 的10个关键区别
- 队列(Queue)--环形队列、优先队列和双向队列
- linux下编写shell获取指定目录下的文件名
- windows 下安装SVN服务器
- scala技术栈
- Python练习(3):浮点数的比较和二分法
- heat创建stack时为何要在keystone新建一个临时project
- Extjs下拉列表树形图