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; mod arr;
struct Solution {} struct Solution {}
use std::collections::VecDeque;
impl Solution { impl Solution {
pub fn can_reach(arr: Vec<i32>, start: i32) -> bool { pub fn get_common(nums1: Vec<i32>, nums2: Vec<i32>) -> i32 {
let start = start as usize; let (mut a, mut b) = (0,0);
if arr[start] == 0 { loop {
return true; if nums1[a] == nums2[b] {
return nums1[a];
} }
let mut depth = vec![arr.len() as i32 + 1; arr.len()]; if nums1[a] < nums2[b] {
depth[start] = 0; a += 1;
let mut queue = VecDeque::new(); if a >= nums1.len() {
let mut inserted = vec![false; arr.len()]; break;
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;
} }
} } else {
return false; b += 1;
}; if b >= nums2.len() {
if y < arr.len() { break;
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;
} }
} }
} }
false -1
} }
} }
fn main() { 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]));
} }