[Swift]LeetCode335. 路径交叉 | Self Crossing
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10261989.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
You are given an array x of n
positive numbers. You start at point (0,0)
and moves x[0]
metres to the north, then x[1]
metres to the west, x[2]
metres to the south, x[3]
metres to the east and so on. In other words, after each move your direction changes counter-clockwise.
Write a one-pass algorithm with O(1)
extra space to determine, if your path crosses itself, or not.
Example 1:
Input: [2,1,1,2]
?????
? ?
???????>
?
Input: true
Explanation: self crossing
Example 2:
Input: [1,2,3,4]
????????
? ?
?
?
?????????????>
Output: false
Explanation: not self crossing
Example 3:
Input: [1,1,1,1]
?????
? ?
?????>
Output: true
Explanation: self crossing
给定一个含有 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
解释: 路径相交了
8ms
1 class Solution { 2 func isSelfCrossing(_ x: [Int]) -> Bool { 3 if x.count < 4 { 4 return false 5 } 6 let c = x.count 7 for i in 0..<c { 8 if (i + 3 < c && x[i] >= x[i + 2] && x[i + 1] <= x[i + 3]) { 9 return true 10 } 11 if (i + 4 < c && x[i + 1] == x[i + 3] && x[i] + x[i + 4] >= x[i + 2]) { 12 return true 13 } 14 if (i + 5 < c && x[i] < x[i + 2] && x[i + 4] < x[i + 2] && x[i + 2] <= x[i] + x[i + 4] && x[i + 1] < x[i + 3] && x[i + 3] <= x[i + 1] + x[i + 5]) { 15 return true 16 } 17 } 18 return false 19 } 20 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了