You are viewing a single comment's thread. Return to all comments →
Rust
fn matching_strings_v2(string_list: &[String], queries: &[String]) -> Vec<i32> { let mut answer:Vec<i32> = vec![]; let mut string_vec = string_list.to_vec(); let mut map = HashMap::<&str, i32>::new(); string_vec.sort_unstable(); for q in queries { map.entry(q) .and_modify(|a| { answer.push(*a); }) .or_insert_with(|| { if let Ok(idx) = string_vec.binary_search(q) { let mut count = 1; count += v2_count_occurence(&string_vec[..], &q, idx, true); count += v2_count_occurence(&string_vec[..], &q, idx, false); answer.push(count); count } else { answer.push(0); 0 } }); } answer } fn v2_count_occurence(arr: &[String] , find: &str, idx: usize, left_or_right: bool) -> i32 { let len = arr.len(); let step = if left_or_right { -1i32 } else { 1 }; let start = idx as i32 + step; let mut i = start; let mut count = 0; loop { let _i = i as usize; if i < 0 || _i >= len { break; } if arr[_i] != find { break; } count += 1; i += step; } count }
Seems like cookies are disabled on this browser, please enable them to open this website
Sparse Arrays
You are viewing a single comment's thread. Return to all comments →
Rust