rs: add «997. Find the Town Judge»

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2024-02-22 16:54:24 +01:00
parent 457b0a97ec
commit 693995acb5
Signed by: mfocko
GPG key ID: 7C47D46246790496

31
rs/find-the-town-judge.rs Normal file
View file

@ -0,0 +1,31 @@
impl Solution {
pub fn find_judge(n: i32, trust: Vec<Vec<i32>>) -> i32 {
let mut trusts: Vec<i32> = vec![0; n as usize];
let mut trusted_by: Vec<i32> = vec![0; n as usize];
// set the counters
for vertices in &trust {
let u = vertices[0] as usize;
let v = vertices[1] as usize;
trusts[u - 1] += 1;
trusted_by[v - 1] += 1;
}
// find the judge
let mut judge = -1;
for i in 0..n as usize {
if trusts[i] != 0 || trusted_by[i] != n - 1 {
continue;
}
if judge != -1 {
return -1;
}
judge = i as i32 + 1;
}
judge
}
}