From 7aae4f81bd83749333400144fa474c918addb7f4 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Mon, 21 Aug 2023 16:29:16 +0800 Subject: [PATCH] =?UTF-8?q?Update=200503.=E4=B8=8B=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E6=9B=B4=E5=A4=A7=E5=85=83=E7=B4=A0II.md=20about=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0503.下一个更大元素II.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/problems/0503.下一个更大元素II.md b/problems/0503.下一个更大元素II.md index d211a680..e732b820 100644 --- a/problems/0503.下一个更大元素II.md +++ b/problems/0503.下一个更大元素II.md @@ -289,6 +289,28 @@ impl Solution { } ``` +> 版本二: + +```rust +impl Solution { + pub fn next_greater_elements(nums: Vec) -> Vec { + let (mut stack, mut res) = (vec![], vec![-1; nums.len()]); + + for i in 0..nums.len() * 2 { + while let Some(&top) = stack.last() { + if nums[i % nums.len()] <= nums[top] { + break; + } + let saved_index = stack.pop().unwrap(); + res[saved_index] = nums[i % nums.len()]; + } + stack.push(i % nums.len()); + } + + res + } +} +```