1855. 下标对中的最大距离
This commit is contained in:
parent
671347dfde
commit
653e68c8f1
52
src/main.rs
52
src/main.rs
|
|
@ -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
|
|
||||||
*/
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue