3761. 镜像对之间最小绝对距离
This commit is contained in:
parent
a467de459b
commit
93d4b712d5
47
src/main.rs
47
src/main.rs
|
|
@ -1,20 +1,51 @@
|
|||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::Entry;
|
||||
|
||||
mod arr;
|
||||
|
||||
struct Solution {}
|
||||
impl Solution {
|
||||
pub fn max_distance(colors: Vec<i32>) -> i32 {
|
||||
fn get_rev(t: i32) -> i32 {
|
||||
let mut t = t;
|
||||
let mut ans = 0;
|
||||
for i in 0..colors.len() {
|
||||
for j in ((i + 1)..colors.len()).rev() {
|
||||
if colors[i] != colors[j] {
|
||||
ans = ans.max((j - i) as i32);
|
||||
}
|
||||
}
|
||||
while t > 0 {
|
||||
ans = ans * 10 + (t % 10);
|
||||
t /= 10;
|
||||
}
|
||||
ans
|
||||
}
|
||||
pub fn min_mirror_pair_distance(nums: Vec<i32>) -> i32 {
|
||||
let mut map = HashMap::<i32, Vec<usize>>::new();
|
||||
for i in 0..nums.len() {
|
||||
map.entry(nums[i]).or_insert_with(Vec::new).push(i);
|
||||
}
|
||||
let mut ans = 1e9 as usize;
|
||||
for i in 0..nums.len() {
|
||||
let x = nums[i];
|
||||
match map.entry(Self::get_rev(x)) {
|
||||
Entry::Occupied(arr) => {
|
||||
//ans = ans.max(i.abs_diff(*arr.get().last().unwrap())).max(i.abs_diff(*arr.get().first().unwrap()));
|
||||
let arr = arr.get();
|
||||
if arr.len() == 1 {
|
||||
if i != arr[0] && arr[0] > i {
|
||||
ans = ans.min(arr[0] - i);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let idx = arr.partition_point(|y| i >= *y);
|
||||
if idx < arr.len() {
|
||||
if i != arr[idx] {
|
||||
ans = ans.min(arr[idx] - i);
|
||||
}
|
||||
}
|
||||
}
|
||||
Entry::Vacant(_) => {}
|
||||
}
|
||||
}
|
||||
if ans == 1e9 as usize { -1 } else { ans as i32 }
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("{:?}", Solution::max_distance(vec![1, 8, 3, 8, 3]));
|
||||
println!("{:?}", Solution::min_mirror_pair_distance(vec![9,9]));
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue