1345. 跳跃游戏 IV
This commit is contained in:
parent
00bc762b5e
commit
6e59cabd84
61
src/main.rs
61
src/main.rs
|
|
@ -1,22 +1,57 @@
|
||||||
mod arr;
|
mod arr;
|
||||||
|
|
||||||
struct Solution {}
|
struct Solution {}
|
||||||
|
use std::collections::hash_map::Entry;
|
||||||
|
use std::collections::{HashMap, VecDeque};
|
||||||
|
|
||||||
impl Solution {
|
impl Solution {
|
||||||
pub fn separate_digits(nums: Vec<i32>) -> Vec<i32> {
|
pub fn min_jumps(arr: Vec<i32>) -> i32 {
|
||||||
let mut ans = vec![];
|
let mut mp = HashMap::new();
|
||||||
for x in nums.iter() {
|
for i in 0..arr.len() {
|
||||||
let mut y = *x;
|
mp.entry(arr[i])
|
||||||
let mut local_ans = vec![];
|
.and_modify(|x: &mut Vec<usize>| x.push(i))
|
||||||
while y > 0 {
|
.or_insert(vec![i]);
|
||||||
local_ans.push(y % 10);
|
|
||||||
y /= 10;
|
|
||||||
}
|
|
||||||
local_ans.reverse();
|
|
||||||
ans.extend(local_ans.iter());
|
|
||||||
}
|
}
|
||||||
ans
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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() {
|
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