LeetCode 1182. Shortest Distance to target color

Problem Statement


use std::collections::HashMap;

impl Solution {
fn get_pos(indices: &Vec<i32>, target: i32) ->usize {
let size = indices.len();
let index = match indices.binary_search(&target) {
Ok(i) => i,
Err(i) => i,
};

if index == 0 {
return indices[0] as usize;
}
if index == size {
return indices[size - 1] as usize;
}
if indices[index] - target < target - indices[index - 1] {
return indices[index] as usize;
} else {
return indices[index - 1] as usize;
}
}

pub fn shortest_distance_color(colors: Vec<i32>, queries: Vec<Vec<i32>>) -> Vec<i32> {
let mut map : HashMap<i32, Vec<i32>> = HashMap::new();
let mut res = vec![];
for i in 0..colors.len() {
let color = colors[i];
if !map.contains_key(&color) {
map.insert(color, vec![i as i32]);
} else {
let mut val = (*map.get(&color).unwrap()).clone();
val.push(i as i32);
map.insert(color, val);
}
}

for q in queries {
let target = q[0];
if !map.contains_key(&q[1]) {
res.push(-1);
continue;
}
let pos = Self::get_pos(map.get(&q[1]).unwrap(), target);
res.push((pos as i32 - target).abs());
}

return res;
}
}