impl Solution { fnget_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] asusize; } if index == size { return indices[size - 1] asusize; } if indices[index] - target < target - indices[index - 1] { return indices[index] asusize; } else { return indices[index - 1] asusize; } }
pubfnshortest_distance_color(colors: Vec<i32>, queries: Vec<Vec<i32>>) -> Vec<i32> { letmut map : HashMap<i32, Vec<i32>> = HashMap::new(); letmut res = vec![]; for i in0..colors.len() { let color = colors[i]; if !map.contains_key(&color) { map.insert(color, vec![i asi32]); } else { letmut val = (*map.get(&color).unwrap()).clone(); val.push(i asi32); 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 asi32 - target).abs()); }