★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-dvjbgvoo-hs.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★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.git
Write a one-pass algorithm with O(1)
extra space to determine, if your path crosses itself, or not.github
Example 1:算法
Input: ????? ? ? ???????> ? Input: true Explanation: self crossing [2,1,1,2]
Example 2:數組
Input: ???????? ? ? ? ? ?????????????> Output: false Explanation: not self crossing [1,2,3,4]
Example 3:微信
Input: ????? ? ? ?????> Output: true Explanation: self crossing[1,1,1,1]
給定一個含有 n
個正數的數組 x。從點 (0,0)
開始,先向北移動 x[0]
米,而後向西移動 x[1]
米,向南移動 x[2]
米,向東移動 x[3]
米,持續移動。也就是說,每次移動後你的方位會發生逆時針變化。spa
編寫一個 O(1)
空間複雜度的一趟掃描算法,判斷你所通過的路徑是否相交。code
示例 1:htm
輸入: ????? ? ? ???????> ? 輸出: true 解釋: 路徑交叉了 [2,1,1,2]
示例 2:blog
輸入: ???????? ? ? ? ? ?????????????> 輸出: false 解釋: 路徑沒有相交 [1,2,3,4]
示例 3:
輸入: ????? ? ? ?????> 輸出: true 解釋: 路徑相交了[1,1,1,1]
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 }