diff --git a/src/main.rs b/src/main.rs index 8e117ee..1b8f332 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,31 +1,25 @@ -use crate::arr::make_string_arr; +use std::collections::HashMap; mod arr; struct Solution {} impl Solution { - fn diff_count_less_two(a: &str, b: &str) -> bool { - let a = a.as_bytes(); - let b = b.as_bytes(); - let mut cnt = 0; - for i in 0..a.len() { - if a[i] != b[i] { - cnt += 1; - if cnt > 2 { - return false; - } - } + pub fn distance(nums: Vec) -> Vec { + let mut ans = vec![0_i64; nums.len()]; + let mut map: HashMap> = HashMap::new(); + for (i, num) in nums.iter().enumerate() { + map.entry(*num).or_insert(vec![]).push(i); } - true - } - pub fn two_edit_words(queries: Vec, dictionary: Vec) -> Vec { - let mut ans = vec![]; - for query in queries { - for dict in dictionary.iter() { - if Self::diff_count_less_two(&query, dict) { - ans.push(query.clone()); - break; - } + for (_, v) in map.into_iter() { + let mut local_len = 0; + for i in 1..v.len() { + local_len += v[i] - v[0]; + } + ans[v[0]] = local_len as i64; + for i in 1..v.len() { + local_len = + local_len - (v[i] - v[i - 1]) * (v.len() - 1 - i) + (v[i] - v[i - 1]) * (i - 1); + ans[v[i]] = local_len as i64; } } ans @@ -33,11 +27,5 @@ impl Solution { } fn main() { - println!( - "{:?}", - Solution::two_edit_words( - make_string_arr(r#"["word","note","ants","wood"]"#), - make_string_arr(r#"["wood","joke","moat"]"#) - ) - ); + println!("{:?}", Solution::distance(vec![1, 3, 1, 1, 2])); }