Skip to content

Commit 896a4ae

Browse files
committed
975
1 parent 22a522b commit 896a4ae

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,7 @@ mod prob_932;
316316
mod prob_946;
317317
mod prob_973;
318318
mod prob_974;
319+
mod prob_975;
319320
mod prob_995;
320321
mod prob_1000;
321322
mod prob_1002;

src/prob_975.rs

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
use std::collections::BTreeMap;
2+
use std::ops::Bound::{Included, Unbounded};
3+
4+
impl Solution {
5+
pub fn odd_even_jumps(a: Vec<i32>) -> i32 {
6+
let n = a.len();
7+
if n == 1 {
8+
return 1;
9+
}
10+
let mut ans = 1;
11+
let mut bt = BTreeMap::new();
12+
let mut odd = vec![false; n];
13+
let mut even = vec![false; n];
14+
bt.insert(a[n-1], n-1);
15+
for i in (0..n-1).rev() {
16+
let cur = a[i];
17+
if let Some((_, &pos)) = bt.range((Included(&cur), Unbounded)).next() {
18+
if pos == n-1 || even[pos] {
19+
odd[i] = true;
20+
ans += 1
21+
}
22+
}
23+
if let Some((_, &pos)) = bt.range((Unbounded, Included(&cur))).rev().next() {
24+
if pos == n-1 || odd[pos] {
25+
even[i] = true;
26+
}
27+
}
28+
bt.insert(cur, i);
29+
}
30+
ans
31+
}
32+
}
33+
34+
struct Solution;
35+
36+
#[cfg(test)]
37+
mod tests {
38+
use super::Solution;
39+
40+
#[test]
41+
fn test_odd_even_jumps() {
42+
let test_cases = vec![
43+
(vec![81,54,96,60,58], 2),
44+
(vec![10,13,12,14,15], 2),
45+
(vec![2,3,1,1,4], 3),
46+
(vec![5,1,3,4,2], 3),
47+
];
48+
for (arr, expect) in test_cases {
49+
assert_eq!(Solution::odd_even_jumps(arr.clone()), expect, "arr: {:?}", arr);
50+
}
51+
}
52+
}

0 commit comments

Comments
 (0)