合并修改 0503.下一个更大元素II

This commit is contained in:
jinbudaily
2023-07-27 14:52:11 +08:00
2 changed files with 105 additions and 0 deletions

View File

@ -975,6 +975,56 @@ impl Solution {
}
```
Rust
双指针
```rust
impl Solution {
pub fn trap(height: Vec<i32>) -> i32 {
let n = height.len();
let mut max_left = vec![0; height.len()];
let mut max_right = vec![0; height.len()];
max_left.iter_mut().zip(max_right.iter_mut().rev()).enumerate().fold((0, 0), |(lm, rm), (idx, (x, y))| {
let lmax = lm.max(height[idx]);
let rmax = rm.max(height[n - 1 - idx]);
*x = lmax; *y = rmax;
(lmax, rmax)
});
height.iter().enumerate().fold(0, |acc, (idx, x)| {
let h = max_left[idx].min(max_right[idx]);
if h > 0 { h - x + acc } else { acc }
})
}
}
```
单调栈
```rust
impl Solution {
pub fn trap(height: Vec<i32>) -> i32 {
let mut stack = vec![];
let mut ans = 0;
for (right_pos, &right_h) in height.iter().enumerate() {
while !stack.is_empty() && height[*stack.last().unwrap()] <= right_h {
let mid_pos = stack.pop().unwrap();
if !stack.is_empty() {
let left_pos = *stack.last().unwrap();
let left_h = height[left_pos];
let top = std::cmp::min(left_h, right_h);
if top > height[mid_pos] {
ans += (top - height[mid_pos]) * (right_pos - left_pos - 1) as i32;
}
}
}
stack.push(right_pos);
}
ans
}
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>

View File

@ -725,6 +725,61 @@ impl Solution {
}
```
Rust
双指针预处理
```rust
impl Solution {
pub fn largest_rectangle_area(v: Vec<i32>) -> i32 {
let n = v.len();
let mut left_smaller_idx = vec![-1; n];
let mut right_smaller_idx = vec![n as i32; n];
for i in 1..n {
let mut mid = i as i32 - 1;
while mid >= 0 && v[mid as usize] >= v[i] {
mid = left_smaller_idx[mid as usize];
}
left_smaller_idx[i] = mid;
}
for i in (0..n-1).rev() {
let mut mid = i + 1;
while mid < n && v[mid] >= v[i] {
mid = right_smaller_idx[mid] as usize;
}
right_smaller_idx[i] = mid as i32;
}
let mut res = 0;
for (idx, &e) in v.iter().enumerate() {
res = res.max((right_smaller_idx[idx] - left_smaller_idx[idx] - 1) * e);
}
dbg!(res)
}
}
```
单调栈
```rust
impl Solution {
pub fn largest_rectangle_area1(mut v: Vec<i32>) -> i32 {
v.insert(0, 0); // 便于使第一个元素能够有左侧<=它的值
v.push(0); // 便于在结束处理最后一个元素后清空残留在栈中的值
let mut res = 0;
let mut stack = vec![]; // 递增的栈
for (idx, &e) in v.iter().enumerate() {
while !stack.is_empty() && v[*stack.last().unwrap()] > e {
let pos = stack.pop().unwrap();
let prev_pos = *stack.last().unwrap();
let s = (idx - prev_pos - 1) as i32 * v[pos];
res = res.max(s);
}
stack.push(idx);
}
res
}
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">