1345. 跳跃游戏 IV
This commit is contained in:
parent
00bc762b5e
commit
6e59cabd84
59
src/main.rs
59
src/main.rs
|
|
@ -1,22 +1,57 @@
|
|||
mod arr;
|
||||
|
||||
struct Solution {}
|
||||
use std::collections::hash_map::Entry;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
|
||||
impl Solution {
|
||||
pub fn separate_digits(nums: Vec<i32>) -> Vec<i32> {
|
||||
let mut ans = vec![];
|
||||
for x in nums.iter() {
|
||||
let mut y = *x;
|
||||
let mut local_ans = vec![];
|
||||
while y > 0 {
|
||||
local_ans.push(y % 10);
|
||||
y /= 10;
|
||||
pub fn min_jumps(arr: Vec<i32>) -> i32 {
|
||||
let mut mp = HashMap::new();
|
||||
for i in 0..arr.len() {
|
||||
mp.entry(arr[i])
|
||||
.and_modify(|x: &mut Vec<usize>| x.push(i))
|
||||
.or_insert(vec![i]);
|
||||
}
|
||||
local_ans.reverse();
|
||||
ans.extend(local_ans.iter());
|
||||
let mut depth = vec![arr.len() as i32 + 1; arr.len()];
|
||||
depth[arr.len() - 1] = 0;
|
||||
let mut queue = VecDeque::new();
|
||||
let mut inserted = vec![false; arr.len()];
|
||||
inserted[arr.len() - 1] = true;
|
||||
queue.push_back(arr.len() - 1);
|
||||
while let Some(x) = queue.pop_front() {
|
||||
if x > 0 {
|
||||
if !inserted[x - 1] {
|
||||
depth[x - 1] = depth[x] + 1;
|
||||
queue.push_back(x - 1);
|
||||
inserted[x - 1] = true;
|
||||
}
|
||||
ans
|
||||
}
|
||||
if x + 1 < arr.len() {
|
||||
if !inserted[x + 1] {
|
||||
depth[x + 1] = depth[x] + 1;
|
||||
queue.push_back(x + 1);
|
||||
inserted[x + 1] = true;
|
||||
}
|
||||
}
|
||||
if let Entry::Occupied(arr) = mp.entry(arr[x]) {
|
||||
for y in arr.get() {
|
||||
if !inserted[*y] {
|
||||
depth[*y] = depth[x] + 1;
|
||||
queue.push_back(*y);
|
||||
inserted[*y] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if inserted[0] {
|
||||
return depth[0];
|
||||
}
|
||||
}
|
||||
-1
|
||||
}
|
||||
}
|
||||
fn main() {
|
||||
println!("{:?}", Solution::separate_digits(vec![13, 25, 83, 77]));
|
||||
println!(
|
||||
"{:?}",
|
||||
Solution::min_jumps(vec![100, -23, -23, 404, 100, 23, 23, 23, 3, 404])
|
||||
);
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue