File tree Expand file tree Collapse file tree 1 file changed +14
-9
lines changed Expand file tree Collapse file tree 1 file changed +14
-9
lines changed Original file line number Diff line number Diff line change @@ -269,18 +269,23 @@ class Solution:
269
269
** 贪心**
270
270
``` golang
271
271
func wiggleMaxLength (nums []int ) int {
272
- var count , preDiff , curDiff int // 初始化默认为0
273
- count = 1 // 初始化为1,因为最小的序列是1个数
274
- if len (nums) < 2 {
275
- return count
272
+ n := len (nums)
273
+ if n < 2 {
274
+ return n
275
+ }
276
+ ans := 1
277
+ prevDiff := nums[1 ] - nums[0 ]
278
+ if prevDiff != 0 {
279
+ ans = 2
276
280
}
277
- for i := 0 ; i < len (nums)-1 ; i++ {
278
- curDiff = nums[i+1 ] - nums[i]
279
- if (curDiff > 0 && preDiff <= 0 ) || (curDiff < 0 && preDiff >= 0 ) {
280
- count++
281
+ for i := 2 ; i < n; i++ {
282
+ diff := nums[i] - nums[i-1 ]
283
+ if diff > 0 && prevDiff <= 0 || diff < 0 && prevDiff >= 0 {
284
+ ans++
285
+ prevDiff = diff
281
286
}
282
287
}
283
- return count
288
+ return ans
284
289
}
285
290
```
286
291
You can’t perform that action at this time.
0 commit comments