Self Crossing
来源:互联网 发布:js得到radio的值 编辑:程序博客网 时间:2024/04/28 06:12
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.
Example 1:
Given x = [2, 1, 1, 2]
,┌───┐│ │└───┼──> │Return true (self crossing)
Example 2:
Given x = [1, 2, 3, 4]
,┌──────┐│ │││└────────────>Return false (not self crossing)
Example 3:
Given x = [1, 1, 1, 1]
,┌───┐│ │└───┼>Return true (self crossing)
这题不会,参考其他人的方法。
实际上相交的情况只有以下三种情况:
x(1) ┌───┐x(2)│ │x(0) └───┼──> x(3)│
第一类是第四条边和第一条边相交的情况,需要满足的条件是第一条边大于等于第三条边,第四条边大于等于第二条边。同样适用于第五条边和第二条边相交,第六条边和第三条边相交等等,依次向后类推的情况...
x(1) ┌──────┐ │ │x(0)x(2)│ ^ │ │x(4) └──────│ x(3)
第二类是第五条边和第一条边重合相交的情况,需要满足的条件是第二条边和第四条边相等,第五条边大于等于第三条边和第一条边的差值,同样适用于第六条边和第二条边重合相交的情况等等依次向后类推...
x(1) ┌──────┐ │ │x(0)x(2)│ <│────│ │ x(5)│x(4) └───────────│ x(3)
第三类是第六条边和第一条边相交的情况,需要满足的条件是第四条边大于等于第二条边,第三条边大于等于第五条边,第五条边大于等于第三条边和第一条边的差值,第六条边大于等于第四条边和第二条边的差值,同样适用于第七条边和第二条边相交的情况等等依次向后类推...
public class Solution { public boolean isSelfCrossing(int[] x) {int m = x.length; for(int i=0; i<m; ++i){ if(i>=3 && x[i]>=x[i-2] && x[i-3]>=x[i-1]) return true; if(i>=4 && x[i-1]==x[i-3] && x[i]+x[i-4]>=x[i-2]) return true; if(i>=5 && x[i-3]>x[i-1] && x[i-2]>x[i-4] && x[i]+x[i-4]>=x[i-2] && x[i-1]+x[i-5]>=x[i-3]) return true; } return false; }}
- 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
- LeetCode335 Self Crossing Java
- [LeetCode] Self Crossing
- 文本自适应(sizeToFit)
- 二分排序算法
- Android Audio Effect 机制初探
- 滴滴出行918编程
- 数据存储总结
- Self Crossing
- word2Vec浅析
- Siemens NX 8.5
- caffe中batch_norm层代码详细注解
- 【转】Qt之文件操作 QFile
- java的四种引用,强弱软虚,用到的场景 (r)
- Java与算法之(8) - 堆排序
- ubuntu中安装android sdk
- 1009. Product of Polynomials (25)