LeetCode 997. Find the Town Judge

Problem Statement


use std::collections::{HashMap, HashSet};

impl Solution {
pub fn find_judge(n: i32, trust: Vec<Vec<i32>>) -> i32 {
let mut map: HashMap<i32, HashSet<i32>> = HashMap::new();
let mut ans = 1;
for p in trust {
let (k, v) = (p[0], p[1]);
map.entry(k).or_insert(HashSet::new());
map.get_mut(&k).unwrap().insert(v);
}

for i in 1..n + 1 {
if ans == i {
continue;
}
if map.contains_key(&ans) {
ans = i;
}
}

for i in 1..n + 1 {
if ans == i {
continue;
}

if map.contains_key(&ans) || map.get(&i).is_none() ||
!map.get(&i).unwrap().contains(&ans) {
return -1;
}
}

return ans;
}
}