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