ARTICLE · INTELLIGENCE

战地情报 · 详情页

来自尧图项目组的一线实战观察与深度解析

元宝 LeetCode 335. Self Crossing Java Implement

元宝    LeetCode 335. Self Crossing Java Implement

Core idea: O(n) scan with three local cases. Simulating the whole path is
“O(n²)”; the key insight is that segment
“i” can only ever intersect segment
“i-3”,
“i-4”, or
“i-5” — everything older is walled off. So one pass with a sliding window of the last 6 lengths is enough.

class Solution {
public boolean isSelfCrossing(int[] x) {
int n = x.length;
for (int i = 3; i < n; i++) {
// Case 1: segment i crosses segment i-3 (transverse crossing)
if (x[i] >= x[i - 2] && x[i - 3] >= x[i - 1]) return true;

// Case 2: segment i overlaps/touches segment i-4 (they are parallel) if (i >= 4 && x[i - 1] == x[i - 3] && x[i] + x[i - 4] >= x[i - 2]) return true; // Case 3: segment i crosses segment i-5 (shrinking spiral closing in) if (i >= 5 && x[i - 2] >= x[i - 4] // i-1 sits inside i-3 && x[i - 1] + x[i - 5] >= x[i - 3] && x[i - 3] >= x[i - 1] && x[i] + x[i - 4] >= x[i - 2]) return true; } return false; }

}

What the three cases mean

  • Case 1 — the spiral has started shrinking: step
    “i” is long enough to reach back past
    “i-2” (
    “x[i] >= x[i-2]”), and
    “i-1” is short enough that
    “i” can slide over it (
    “x[i-3] >= x[i-1]”). Example
    “[2,1,1,2]”: the 4th side cuts straight through the 1st.
  • Case 2 —
    “i” and
    “i-4” run parallel on the same line (that’s what
    “x[i-1] == x[i-3]” expresses), and their spans overlap. This catches touching, not just crossing, so
    “[1,1,1,1]” returns
    “true”.
  • Case 3 — the innermost coil:
    “i” reaches back over
    “i-5” while
    “i-1” is nested inside
    “i-3”. All four inequalities together pin the overlap in both axes.

Key points

  • The loop starts at
    “i = 3” since fewer than 4 segments can never self-cross.
  • Conditions are
    “>=”, not
    “>” — a path that merely touches an earlier point counts as crossing.

“x[i] + x[i-4]” stays well within
“int” for the given constraints (
“x[i] ≤ 10^5”); switch to
“long” if values can approach
“10^9”.

Complexity:
“O(n)” time,
“O(1)” space.

Verified against a brute-force geometry check (build the polyline, test every non-adjacent segment pair, including parallel overlap and endpoint touching): exhaustive over all arrays of length ≤ 7 with values 1–4 (21,844 cases), plus 260,000 random cases up to length 32. All match. Official samples:
“[2,1,1,2] → true”,
“[1,2,3,4] → false”,
“[1,1,1,1] → true”.
“n = 100,000” runs in under 1 ms.

RELATED READING

延伸阅读

更多一线实战笔记与深度复盘,助您持续精进