1855. 下标对中的最大距离

This commit is contained in:
li_chx 2026-04-20 09:18:53 +08:00
parent 671347dfde
commit 653e68c8f1
Signed by: li_chx
GPG Key ID: C7CF27EFA1E58BAC
1 changed files with 11 additions and 41 deletions

View File

@ -1,52 +1,22 @@
use crate::arr::make_string_arr;
use std::collections::HashMap;
mod arr; mod arr;
struct Solution {} struct Solution {}
impl Solution { impl Solution {
pub fn closest_target(words: Vec<String>, target: String, start_index: i32) -> i32 { pub fn max_distance(nums1: Vec<i32>, nums2: Vec<i32>) -> i32 {
let n = words.len(); let mut ans = 0;
let map = words.into_iter().enumerate().fold( for i in 0..nums1.len() {
HashMap::<String, Vec<usize>>::new(), let mut idx = nums2.partition_point(|&x| x >= nums1[i]);
|mut acc, (i, word)| { if idx == 0 {
acc.entry(word).or_default().push(i); continue;
acc
},
);
if map.contains_key(&target) {
let arr = map.get(&target).unwrap();
let idx = arr.partition_point(|&x| x < start_index as usize);
let a = arr[idx % arr.len()].abs_diff(start_index as usize);
let b = arr[(idx + arr.len() - 1) % arr.len()].abs_diff(start_index as usize);
a.min(n - a).min(b).min(n - b) as i32
} else {
-1
} }
idx -= 1;
ans = ans.max(idx as i32 - i as i32);
}
ans
} }
} }
fn main() { fn main() {
println!( println!("{:?}", Solution::max_distance(vec![55,30,5,4,2],vec![100,20,10,10,5]));
"{:?}",
Solution::closest_target(
make_string_arr(r#"["hello","i","am","leetcode","hello"]"#),
"hello".to_string(),
1
)
);
} }
/*
[[-86, 2], [-76, 2], [-46, 2]]
[-84, -59]
[[0, 2, 29], [0, 2, 10], [0, 2, 10]]
10
-8 -6 -4 -2
-86 -74 -46 -29
-84 -60 -59
-7 -5 -3
*/