|
| 1 | +# 335. Self Crossing |
| 2 | +You are given an array of integers `distance`. |
| 3 | + |
| 4 | +You start at the point `(0, 0)` on an **X-Y plane**, and you move `distance[0]` meters to the north, then `distance[1]` meters to the west, `distance[2]` meters to the south, `distance[3]` meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise. |
| 5 | + |
| 6 | +Return `true` *if your path crosses itself or* `false` *if it does not*. |
| 7 | + |
| 8 | +#### Example 1: |
| 9 | + |
| 10 | +<pre> |
| 11 | +<strong>Input:</strong> distance = [2,1,1,2] |
| 12 | +<strong>Output:</strong> true |
| 13 | +<strong>Explanation:</strong> The path crosses itself at the point (0, 1). |
| 14 | +</pre> |
| 15 | + |
| 16 | +#### Example 2: |
| 17 | + |
| 18 | +<pre> |
| 19 | +<strong>Input:</strong> distance = [1,2,3,4] |
| 20 | +<strong>Output:</strong> false |
| 21 | +<strong>Explanation:</strong> The path does not cross itself at any point. |
| 22 | +</pre> |
| 23 | + |
| 24 | +#### Example 3: |
| 25 | + |
| 26 | +<pre> |
| 27 | +<strong>Input:</strong> distance = [1,1,1,2,1] |
| 28 | +<strong>Output:</strong> true |
| 29 | +<strong>Explanation:</strong> The path crosses itself at the point (0, 0). |
| 30 | +</pre> |
| 31 | + |
| 32 | +#### Constraints: |
| 33 | +* <code>1 <= distance.length <= 10<sup>5</sup></code> |
| 34 | +* <code>1 <= distance[i] <= 10<sup>5</sup></code> |
| 35 | + |
| 36 | +## Solutions (Rust) |
| 37 | + |
| 38 | +### 1. Solution |
| 39 | +```Rust |
| 40 | +impl Solution { |
| 41 | + pub fn is_self_crossing(mut distance: Vec<i32>) -> bool { |
| 42 | + let mut i = 2; |
| 43 | + |
| 44 | + while i < distance.len() { |
| 45 | + if distance[i] <= distance[i - 2] { |
| 46 | + let mut tmp = distance[i - 2]; |
| 47 | + if i > 3 { |
| 48 | + tmp -= distance[i - 4]; |
| 49 | + } |
| 50 | + if i > 2 && distance[i] >= tmp { |
| 51 | + distance[i - 1] -= distance[i - 3]; |
| 52 | + } |
| 53 | + break; |
| 54 | + } |
| 55 | + |
| 56 | + i += 1; |
| 57 | + } |
| 58 | + |
| 59 | + while i < distance.len() - 1 { |
| 60 | + i += 1; |
| 61 | + |
| 62 | + if distance[i] >= distance[i - 2] { |
| 63 | + return true; |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + false |
| 68 | + } |
| 69 | +} |
| 70 | +``` |
0 commit comments