1345. 跳跃游戏 IV

This commit is contained in:
li_chx 2026-05-18 16:46:04 +08:00
parent 00bc762b5e
commit 6e59cabd84
Signed by: li_chx
GPG Key ID: C7CF27EFA1E58BAC
1 changed files with 48 additions and 13 deletions

View File

@ -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])
);
}