1
1
package com .fishercoder .solutions ;
2
2
3
- /**
4
- * 335. Self Crossing
5
- *
6
- * You are given an array x of n positive numbers.
7
- * You start at point (0,0) and moves x[0] metres to the north,
8
- * then x[1] metres to the west,
9
- * x[2] metres to the south,
10
- * x[3] metres to the east and so on.
11
- * In other words, after each move your direction changes counter-clockwise.
12
-
13
- Write a one-pass algorithm with O(1) extra space to determine, if your path crosses itself, or not.
14
-
15
- Example 1:
16
- Given x =
17
- [2, 1, 1, 2]
18
- ,
19
- ?????
20
- ? ?
21
- ???????>
22
- ?
23
-
24
- Return true (self crossing)
25
- Example 2:
26
- Given x =
27
- [1, 2, 3, 4]
28
- ,
29
- ????????
30
- ? ?
31
- ?
32
- ?
33
- ?????????????>
34
-
35
- Return false (not self crossing)
36
- Example 3:
37
- Given x =
38
- [1, 1, 1, 1]
39
- ,
40
- ?????
41
- ? ?
42
- ?????>
43
-
44
- Return true (self crossing)
45
-
46
- */
47
3
public class _335 {
48
4
public static class Solution1 {
49
- /** reference: https://discuss.leetcode.com/topic/38014/java-oms-with-explanation/2 */
5
+ /**
6
+ * reference: https://discuss.leetcode.com/topic/38014/java-oms-with-explanation/2
7
+ */
50
8
public boolean isSelfCrossing (int [] x ) {
51
9
int l = x .length ;
52
10
if (l <= 3 ) {
@@ -64,9 +22,9 @@ public boolean isSelfCrossing(int[] x) {
64
22
}
65
23
if (i >= 5 ) {
66
24
if (x [i - 2 ] - x [i - 4 ] >= 0
67
- && x [i ] >= x [i - 2 ] - x [i - 4 ]
68
- && x [i - 1 ] >= x [i - 3 ] - x [i - 5 ]
69
- && x [i - 1 ] <= x [i - 3 ]) {
25
+ && x [i ] >= x [i - 2 ] - x [i - 4 ]
26
+ && x [i - 1 ] >= x [i - 3 ] - x [i - 5 ]
27
+ && x [i - 1 ] <= x [i - 3 ]) {
70
28
return true ; // Sixth line crosses first line and onward
71
29
}
72
30
}
0 commit comments