Skip to content

Commit f2e4d95

Browse files
committed
src/bin/find-the-minimum-and-maximum-number-of-nodes-between-critical-points.rs
1 parent 6166ec2 commit f2e4d95

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
#![allow(dead_code, unused, unused_variables, non_snake_case)]
2+
3+
fn main() {}
4+
5+
struct Solution;
6+
7+
// Definition for singly-linked list.
8+
#[derive(PartialEq, Eq, Clone, Debug)]
9+
pub struct ListNode {
10+
pub val: i32,
11+
pub next: Option<Box<ListNode>>,
12+
}
13+
14+
impl ListNode {
15+
#[inline]
16+
fn new(val: i32) -> Self {
17+
ListNode { next: None, val }
18+
}
19+
}
20+
21+
impl Solution {
22+
pub fn nodes_between_critical_points(head: Option<Box<ListNode>>) -> Vec<i32> {
23+
let mut min_distance = i32::MAX;
24+
let mut pre_value = head.as_ref().unwrap().val;
25+
let mut pre_index = 0; // 前一个节点的下标
26+
let mut first_index = None; // 第一个极值的下标
27+
let mut pre_index_1 = None; // 前一个极值的下标
28+
29+
let mut current = head.unwrap().next;
30+
while current.is_some() {
31+
let mut c = current.unwrap();
32+
let current_val = c.val;
33+
let next = c.next.take();
34+
if next.is_some() {
35+
let next_value = next.as_ref().unwrap().val;
36+
if (current_val < pre_value && current_val < next_value)
37+
|| (current_val > pre_value && current_val > next_value)
38+
{
39+
if first_index.is_none() {
40+
first_index = Some(pre_index + 1);
41+
}
42+
43+
if let Some(x) = pre_index_1 {
44+
min_distance = min_distance.min(pre_index + 1 - x);
45+
}
46+
47+
pre_index_1 = Some(pre_index + 1);
48+
}
49+
}
50+
51+
pre_index += 1;
52+
current = next;
53+
pre_value = current_val;
54+
}
55+
56+
if first_index != pre_index_1 {
57+
vec![min_distance, pre_index_1.unwrap() - first_index.unwrap()]
58+
} else {
59+
vec![-1, -1]
60+
}
61+
}
62+
}

0 commit comments

Comments
 (0)