敢教日月换新天。为有牺牲多壮志,

[Swift]LeetCode335. 路径交叉 | Self Crossing

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10261989.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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 }
复制代码

 

posted @   为敢技术  阅读(252)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示
哥伦布
09:09发布
哥伦布
09:09发布
3°
多云
东南风
3级
空气质量
相对湿度
47%
今天
中雨
3°/15°
周三
中雨
3°/13°
周四
小雪
-1°/6°