335. 路径交叉

给定一个含有 n 个正数的数组 x。从点 (0,0) 开始,先向北移动 x[0] 米,然后向西移动 x[1] 米,向南移动 x[2] 米,向东移动 x[3] 米,持续移动。也就是说,每次移动后你的方位会发生逆时针变化。

编写一个 O(1) 空间复杂度的一趟扫描算法,判断你所经过的路径是否相交。

示例 1:

┌───┐
│   │
└───┼──>
    │

输入: [2,1,1,2]
输出: true
示例 2:

┌──────┐
│      │


└────────────>

输入: [1,2,3,4]
输出: false
示例 3:

┌───┐
│   │
└───┼>

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/self-crossing

扫描二维码关注公众号,回复: 11460958 查看本文章

画图水题

class Solution:
    def isSelfCrossing(self, x: List[int]) -> bool:
        n=len(x)
        if n<4:
            return False
        for i in range(3,n):
            if x[i]>=x[i-2] and x[i-1]<=x[i-3]:
                return True
            if x[i-1]<=x[i-3] and x[i-2]<=x[i]:
                return True
            if i>3 and x[i-1]==x[i-3] and x[i]+x[i-4]==x[i-2]:
                return True
            if i>4 and x[i]+x[i-4]>=x[i-2] and x[i-1]>=x[i-3]-x[i-5]\
                    and x[i-1]<=x[i-3] and x[i-2]>=x[i-4] and x[i-3]>=x[i-5]:
                return True
        return False    

猜你喜欢

转载自www.cnblogs.com/xxxsans/p/13391293.html