From 2f1cd225eea3fff9f76c2054f7b3472b7ed24cfd Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Mon, 6 Mar 2023 11:41:46 +0800 Subject: [PATCH 1/2] =?UTF-8?q?Update=200376.=E6=91=86=E5=8A=A8=E5=BA=8F?= =?UTF-8?q?=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0376.摆动序列.md | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/problems/0376.摆动序列.md b/problems/0376.摆动序列.md index efb9c6b6..d4daccc5 100644 --- a/problems/0376.摆动序列.md +++ b/problems/0376.摆动序列.md @@ -462,21 +462,19 @@ var wiggleMaxLength = function(nums) { ```Rust impl Solution { pub fn wiggle_max_length(nums: Vec) -> i32 { - let len = nums.len() as usize; - if len <= 1 { - return len as i32; + if nums.len() == 1 { + return 1; } - let mut preDiff = 0; - let mut curDiff = 0; - let mut result = 1; - for i in 0..len-1 { - curDiff = nums[i+1] - nums[i]; - if (preDiff <= 0 && curDiff > 0) || (preDiff >= 0 && curDiff < 0) { - result += 1; - preDiff = curDiff; + let mut res = 1; + let mut pre_diff = 0; + for i in 0..nums.len() - 1 { + let cur_diff = nums[i + 1] - nums[i]; + if (pre_diff <= 0 && cur_diff > 0) || (pre_diff >= 0 && cur_diff < 0) { + res += 1; + pre_diff = cur_diff; } } - result + res } } ``` From 30b5b629a288a380f21dcda11d6f8be5d9e17f10 Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Mon, 6 Mar 2023 12:24:23 +0800 Subject: [PATCH 2/2] =?UTF-8?q?Update=200376.=E6=91=86=E5=8A=A8=E5=BA=8F?= =?UTF-8?q?=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0376.摆动序列.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0376.摆动序列.md b/problems/0376.摆动序列.md index d4daccc5..0199d83b 100644 --- a/problems/0376.摆动序列.md +++ b/problems/0376.摆动序列.md @@ -479,6 +479,30 @@ impl Solution { } ``` +**动态规划** + +```rust +impl Solution { + pub fn wiggle_max_length(nums: Vec) -> i32 { + if nums.len() == 1 { + return 1; + } + let (mut down, mut up) = (1, 1); + for i in 1..nums.len() { + // i - 1 为峰顶 + if nums[i] < nums[i - 1] { + down = down.max(up + 1); + } + // i - 1 为峰谷 + if nums[i] > nums[i - 1] { + up = up.max(down + 1); + } + } + down.max(up) + } +} +``` + ### C **贪心**