From 8329c3d6d14c16630d6c8a8303ed7fab4080d02f Mon Sep 17 00:00:00 2001 From: 0407-zh Date: Mon, 5 Sep 2022 10:50:27 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0376.=E6=91=86=E5=8A=A8?= =?UTF-8?q?=E5=BA=8F=E5=88=97=20=E8=B4=AA=E5=BF=83=E7=AE=97=E6=B3=95Go?= =?UTF-8?q?=E8=AF=AD=E8=A8=80=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0376.摆动序列.md | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/problems/0376.摆动序列.md b/problems/0376.摆动序列.md index d15ed2d0..fef5e594 100644 --- a/problems/0376.摆动序列.md +++ b/problems/0376.摆动序列.md @@ -269,18 +269,23 @@ class Solution: **贪心** ```golang func wiggleMaxLength(nums []int) int { - var count, preDiff, curDiff int //初始化默认为0 - count = 1 // 初始化为1,因为最小的序列是1个数 - if len(nums) < 2 { - return count + n := len(nums) + if n < 2 { + return n } - for i := 0; i < len(nums)-1; i++ { - curDiff = nums[i+1] - nums[i] - if (curDiff > 0 && preDiff <= 0) || (curDiff < 0 && preDiff >= 0) { - count++ + ans := 1 + prevDiff := nums[1] - nums[0] + if prevDiff != 0 { + ans = 2 + } + for i := 2; i < n; i++ { + diff := nums[i] - nums[i-1] + if diff > 0 && prevDiff <= 0 || diff < 0 && prevDiff >= 0 { + ans++ + prevDiff = diff } } - return count + return ans } ```