Skip to content

Commit 881ddb1

Browse files
authored
优化 0376. 摆动序列 python3版本
优化 0376. 摆动序列 python3版本
1 parent a4b7399 commit 881ddb1

File tree

1 file changed

+8
-12
lines changed

1 file changed

+8
-12
lines changed

problems/0376.摆动序列.md

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -138,20 +138,16 @@ class Solution {
138138
```
139139

140140
Python:
141-
```python
141+
```python3
142142
class Solution:
143143
def wiggleMaxLength(self, nums: List[int]) -> int:
144-
#贪心 求波峰数量 + 波谷数量
145-
if len(nums)<=1:
146-
return len(nums)
147-
cur, pre = 0,0 #当前一对差值,前一对差值
148-
count = 1#默认最右边有一个峰值
149-
for i in range(len(nums)-1):
150-
cur = nums[i+1] - nums[i]
151-
if((cur>0 and pre<=0) or (cur<0 and pre>=0)):
152-
count += 1
153-
pre = cur
154-
return count
144+
preC,curC,res = 0,0,1 #题目里nums长度大于等于1,当长度为1时,其实到不了for循环里去,所以不用考虑nums长度
145+
for i in range(len(nums) - 1):
146+
curC = nums[i + 1] - nums[i]
147+
if curC * preC <= 0 and curC !=0: #差值为0时,不算摆动
148+
res += 1
149+
preC = curC #如果当前差值和上一个差值为一正一负时,才需要用当前差值替代上一个差值
150+
return res
155151
```
156152

157153
Go:

0 commit comments

Comments
 (0)