@@ -77,14 +77,15 @@ https://leetcode-cn.com/problems/self-crossing/
7777
7878![ ] ( https://pic.leetcode-cn.com/1635437888-JuQzXp-007S8ZIlly1ghltxkbce9j30ro0o676d.jpg )
7979
80+ > 图有误,第一种和第二种是同一种情况,换个角度看一样了。文字解释和代码已经更正
81+
8082这个时候代码就呼之欲出了。
8183
8284- 我们只需要遍历数组 x,假设当前是第 i 个元素。
8385- 如果 x[ i] >= x[ i - 2] and x[ i - 1] <= x[ i - 3] ,则相交(第一种情况)
84- - 如果 x[ i - 1] <= x[ i - 3] and x[ i - 2] <= x[ i] ,则相交(第二种情况)
85- - 如果 i > 3 and x[ i - 1] == x[ i - 3] and x[ i] + x[ i - 4] == x[ i - 2] ,则相交(第三种情况)
86+ - 如果 i > 3 and x[ i - 1] == x[ i - 3] and x[ i] + x[ i - 4] == x[ i - 2] ,则相交(第二种情况)
8687- 如果 i > 4 and x[ i] + x[ i - 4] >= x[ i - 2] and x[ i - 1] >= x[ i - 3] - x[ i - 5] \
87- and x[ i - 1] <= x[ i - 3] and x[ i - 2] >= x[ i - 4] and x[ i - 3] >= x[ i - 5] ,则相交(第四种情况 )
88+ and x[ i - 1] <= x[ i - 3] and x[ i - 2] >= x[ i - 4] and x[ i - 3] >= x[ i - 5] ,则相交(第三种情况 )
8889- 否则不相交
8990
9091## 关键点解析
@@ -97,6 +98,8 @@ https://leetcode-cn.com/problems/self-crossing/
9798
9899我们采用的是滚动数组。如果你了解动态规划的滚动数组优化的话应该理解我的意思 。但是难点就在于我们怎么知道当前状态和哪几个有关。对于这道题来说,画图或许可以帮助你打开思路。另外面试的时候说出$O(B)$的思路也不失为一个帮助你冷静分析问题的手段。
99100
101+ 感谢 [ @saberjiang-b ] ( https://leetcode-cn.com/u/saberjiang-b/ ) 指出的代码重复判断问题
102+
100103## 代码
101104
102105代码支持:Python3
@@ -112,8 +115,6 @@ class Solution:
112115 for i in range (3 , n):
113116 if x[i] >= x[i - 2 ] and x[i - 1 ] <= x[i - 3 ]:
114117 return True
115- if x[i - 1 ] <= x[i - 3 ] and x[i - 2 ] <= x[i]:
116- return True
117118 if i > 3 and x[i - 1 ] == x[i - 3 ] and x[i] + x[i - 4 ] == x[i - 2 ]:
118119 return True
119120 if i > 4 and x[i] + x[i - 4 ] >= x[i - 2 ] and x[i - 1 ] >= x[i - 3 ] - x[i - 5 ] \
@@ -131,4 +132,6 @@ class Solution:
131132
132133大家对此有何看法,欢迎给我留言,我有时间都会一一查看回答。更多算法套路可以访问我的 LeetCode 题解仓库:https://github.com/azl397985856/leetcode 。 目前已经 45K star 啦。
133134大家也可以关注我的公众号《力扣加加》带你啃下算法这块硬骨头。
135+
136+
134137![ ] ( https://tva1.sinaimg.cn/large/007S8ZIlly1gfcuzagjalj30p00dwabs.jpg )
0 commit comments