Skip to content

Commit 96d1d57

Browse files
Merge pull request youngyangyang04#1626 from 0407-zh/master
更新376.摆动序列 贪心算法Go语言版本
2 parents a5723e1 + 8329c3d commit 96d1d57

File tree

1 file changed

+14
-9
lines changed

1 file changed

+14
-9
lines changed

problems/0376.摆动序列.md

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -269,18 +269,23 @@ class Solution:
269269
**贪心**
270270
```golang
271271
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
276280
}
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
281286
}
282287
}
283-
return count
288+
return ans
284289
}
285290
```
286291

0 commit comments

Comments
 (0)