2540. 最小公共值

This commit is contained in:
li_chx 2026-05-19 11:44:18 +08:00
parent afa91fe380
commit 44ce8b9fd4
Signed by: li_chx
GPG Key ID: C7CF27EFA1E58BAC
1 changed files with 17 additions and 36 deletions

View File

@ -1,49 +1,30 @@
mod arr;
struct Solution {}
use std::collections::VecDeque;
impl Solution {
pub fn can_reach(arr: Vec<i32>, start: i32) -> bool {
let start = start as usize;
if arr[start] == 0 {
return true;
pub fn get_common(nums1: Vec<i32>, nums2: Vec<i32>) -> i32 {
let (mut a, mut b) = (0,0);
loop {
if nums1[a] == nums2[b] {
return nums1[a];
}
let mut depth = vec![arr.len() as i32 + 1; arr.len()];
depth[start] = 0;
let mut queue = VecDeque::new();
let mut inserted = vec![false; arr.len()];
inserted[start] = true;
queue.push_back(start);
while let Some(x) = queue.pop_front() {
let y = x + arr[x] as usize;
let mut func = |inserted: &mut Vec<bool>, y: usize| -> bool {
if !inserted[y] {
depth[y] = depth[x] + 1;
queue.push_back(y);
(*inserted)[y] = true;
if arr[y] == 0 {
return true;
if nums1[a] < nums2[b] {
a += 1;
if a >= nums1.len() {
break;
}
}
return false;
};
if y < arr.len() {
if func(&mut inserted, y) {
return true;
}
}
let y = x as i32 - arr[x];
if y >= 0 {
let y = y as usize;
if func(&mut inserted, y) {
return true;
} else {
b += 1;
if b >= nums2.len() {
break;
}
}
}
false
-1
}
}
fn main() {
println!("{:?}", Solution::can_reach(vec![4, 2, 3, 0, 3, 1, 2], 5));
println!("{:?}", Solution::get_common(vec![1,2,3,6], vec![2,3,4,5]));
}