leetcode_335 Self Crossing
来源:互联网 发布:澳洲gdp数据 编辑:程序博客网 时间:2024/06/14 03:39
题意分析: 定一个数组x,代表行走的距离,最初的方向是北,每走一步就按逆时针顺序变化方向(北,西,南,东)要求只遍历一次x,并且用O(1)的存储空间,判断走过的路径是否交叉。
解题思路:
方法1:分南北和东西方向进行判断
出现交叉的情况是:第四条边和第一条边相交,需满足条件是第一条边大于等于第三条边,第四条边大于等于第二天便。同样适用于第五条边和第二条边相交,第六条边与第三条边相交等等,依次向后类推,其实现具体如下程序。
C++实现
bool isSelfCrossing(vector<int> &x){ int n = x.size(); if (n < 4) return false; int t1 = 0; int t2 = x[0]; int t3 = x[1]; int t4 = x[2]; int t5; // 判断东西方面是否满足交叉 bool increase = t4 > t2 ? true : false; for (int i = 3; i < n; i++) { t5 = x[i]; // 东西方向不满足满足交叉,南北方向不满足交叉 if (increase && t3 >= t5) { // 在后续中,不满足交叉条件 if (t5 + t1 < t3 || i + 1 < n && x[i + 1] + t2 < t4) increase = false; // 满足交叉条件 else if (i + 1 < n) return true; } // 东西方向和南北方向均满足交叉情况 else if (!increase && t3 <= t5) return true; // 交换数据,用于下次判断 t1 = t2; t2 = t3; t3 = t4; t4 = t5; } return false;}
Java实现
public boolean isSelfCrossing(int [] x) { int n = x.length; if (n < 4) return false; int t1 = 0; int t2 = x[0]; int t3 = x[1]; int t4 = x[2]; int t5; boolean increase = t4 > t2 ? true : false; for (int i = 3; i < n; i++) { t5 = x[i]; if (increase && t2 >= t5) { if (t5 + t1 < t3 || i + 1 < n && x[i + 1] + t2 < t4) { increase = false; } else if (i + 1 < n) { return true; } } else if (!increase && t3 <= t5) { return true; } t1 = t2; t2 = t3; t3 = t4; t4 = t5; } return false;}
参考文献
http://www.cnblogs.com/grandyang/p/5216856.html
https://www.hrwhisper.me/leetcode-self-crossing/
0 0
- leetcode_335 Self Crossing
- leetcode_335. Self Crossing ? 待解决
- Self Crossing
- Self Crossing
- Self Crossing
- [leetcode]335. Self Crossing
- [LeetCode]Self Crossing
- leetcode 335. Self Crossing
- [LeetCode] 335. Self Crossing
- leetcode - Self Crossing
- leedCode 335 Self Crossing
- [leetcode] 335. Self Crossing
- [leetcode] Self Crossing
- [LeetCode 335] Self Crossing
- LeetCode Self Crossing
- 335. Self Crossing
- [leetcode-335]Self Crossing
- Leetcode Self Crossing
- sql查询优化 索引优化
- c高级字长字节序对齐
- hdu_1848(SG函数)
- Java面试汇总
- 困扰我的isset/empty函数
- leetcode_335 Self Crossing
- [bzoj1014][JSOI2008]火星人prefix
- Eclipse Mars中Cordova 开发
- c高级预处理
- 翻墙?隐私?今天聊聊VPN的那些事儿
- 拉格朗日插值法
- HTTP/2.0 中英文对照
- Mysql InnoDB行锁实现方式
- UVA-1588-Kickdown:简单字符串匹配