335. 路径交叉

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

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

 

示例 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

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

 

画图,分类讨论

 

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 Trueif 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    

 

posted @ 2020-07-28 15:17  XXXSANS  阅读(235)  评论(0编辑  收藏  举报