From ef44e750cec20980095e63db3c090c8df48f620c Mon Sep 17 00:00:00 2001 From: Guanzhong Pan Date: Mon, 11 Apr 2022 20:34:32 +0100 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200376.=E6=91=86=E5=8A=A8?= =?UTF-8?q?=E5=BA=8F=E5=88=97.md=20C=E8=AF=AD=E8=A8=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0376.摆动序列.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0376.摆动序列.md b/problems/0376.摆动序列.md index 5076c9ad..6bd2277f 100644 --- a/problems/0376.摆动序列.md +++ b/problems/0376.摆动序列.md @@ -298,5 +298,32 @@ var wiggleMaxLength = function(nums) { }; ``` +### C +**贪心** +```c +int wiggleMaxLength(int* nums, int numsSize){ + if(numsSize <= 1) + return numsSize; + + int length = 1; + int preDiff , curDiff; + preDiff = curDiff = 0; + for(int i = 0; i < numsSize - 1; ++i) { + // 计算当前i元素与i+1元素差值 + curDiff = nums[i+1] - nums[i]; + + // 若preDiff与curDiff符号不符,则子序列长度+1。更新preDiff的符号 + // 若preDiff与curDiff符号一致,当前i元素为连续升序/连续降序子序列的中间元素。不被记录入长度 + // 注:当preDiff为0时,curDiff为正或为负都属于符号不同 + if((curDiff > 0 && preDiff <= 0) || (preDiff >= 0 && curDiff < 0)) { + preDiff = curDiff; + length++; + } + } + + return length; +} +``` + -----------------------