LeetCode 题解工作台

路径交叉

给你一个整数数组 distance 。 从 X-Y 平面上的点 (0,0) 开始,先向北移动 distance[0] 米,然后向西移动 distance[1] 米,向南移动 distance[2] 米,向东移动 distance[3] 米,持续移动。也就是说,每次移动后你的方位会发生逆时针变化。 判…

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

困难 · 数组·数学

bolt

答案摘要

class Solution: def isSelfCrossing(self, distance: List[int]) -> bool:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 distance

X-Y 平面上的点 (0,0) 开始,先向北移动 distance[0] 米,然后向西移动 distance[1] 米,向南移动 distance[2] 米,向东移动 distance[3] 米,持续移动。也就是说,每次移动后你的方位会发生逆时针变化。

判断你所经过的路径是否相交。如果相交,返回 true ;否则,返回 false

 

示例 1:

输入:distance = [2,1,1,2]
输出:true

示例 2:

输入:distance = [1,2,3,4]
输出:false

示例 3:

输入:distance = [1,1,1,1]
输出:true

 

提示:

  • 1 <= distance.length <= 105
  • 1 <= distance[i] <= 105
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:
    def isSelfCrossing(self, distance: List[int]) -> bool:
        d = distance
        for i in range(3, len(d)):
            if d[i] >= d[i - 2] and d[i - 1] <= d[i - 3]:
                return True
            if i >= 4 and d[i - 1] == d[i - 3] and d[i] + d[i - 4] >= d[i - 2]:
                return True
            if (
                i >= 5
                and d[i - 2] >= d[i - 4]
                and d[i - 1] <= d[i - 3]
                and d[i] >= d[i - 2] - d[i - 4]
                and d[i - 1] + d[i - 5] >= d[i - 3]
            ):
                return True
        return False
speed

复杂度分析

指标
时间complexity is O(n) since each distance is evaluated once against a constant number of prior distances. Space complexity is O(1) using fixed variables to track previous steps instead of simulating coordinates.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Are you considering edge cases where the path touches but does not cross previous segments?

  • question_mark

    Notice if your solution handles sequences that expand then contract, creating potential intersections.

  • question_mark

    Can you simplify checks by using only the last few distances instead of full coordinate storage?

warning

常见陷阱

外企场景
  • error

    Simulating full coordinates unnecessarily increases space usage and complexity.

  • error

    Failing to check the fourth or fifth previous distance can miss overlapping loops.

  • error

    Incorrectly assuming only consecutive steps can cause crossing ignores geometric patterns.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Detect self-crossing in a 3D path with directional changes in three axes.

  • arrow_right_alt

    Find the first step where the path crosses itself and return its index.

  • arrow_right_alt

    Determine if a path is self-avoiding given a repeated move sequence of arbitrary length.

help

常见问题

外企场景

路径交叉题解:数组·数学 | LeetCode #335 困难