LeetCode 1136. Parallel Courses

Problem Statement

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

impl Solution {
pub fn minimum_semesters(n: i32, relations: Vec<Vec<i32>>) -> i32 {
let mut in_degrees = vec![0; n as usize + 1];
let mut map: HashMap<i32, HashSet<i32>> = HashMap::new();
for r in &relations {
map.entry(r[0]).or_insert(HashSet::new());
map.get_mut(&r[0]).unwrap().insert(r[1]);
in_degrees[r[1] as usize] += 1;
}

let mut q = VecDeque::new();
let (mut ans, mut sum) = (0, 0);
for i in 1..n + 1 {
if in_degrees[i as usize] == 0 {
q.push_back(i);
}
}

while !q.is_empty() {
let size = q.len();
sum += size;
for _i in 0..size {
let cur = q.front().unwrap().clone();
q.pop_front();
if !map.contains_key(&cur) {
continue;
}
for next in map.get(&cur).unwrap() {
in_degrees[*next as usize] -= 1;
if in_degrees[*next as usize] == 0 {
q.push_back(*next);
}
}
}
ans += 1;
}
if sum == n as usize {
return ans;
} else {
return -1;
}
}
}

LeetCode 1213. Intersection of Three Sorted Arrays

Problem Statement


use std::cmp;

impl Solution {
pub fn arrays_intersection(arr1: Vec<i32>, arr2: Vec<i32>, arr3: Vec<i32>) -> Vec<i32> {
let mut ans = vec![];
let (mut i, mut j, mut k) = (0, 0, 0);

while i < arr1.len() && j < arr2.len() && k < arr3.len() {
if arr1[i] == arr2[j] && arr2[j] == arr3[k] {
ans.push(arr1[i]);
}
let min_val = cmp::min(arr1[i], cmp::min(arr2[j], arr3[k]));
if arr1[i] == min_val {
i += 1;
}
if arr2[j] == min_val {
j += 1;
}
if arr3[k] == min_val {
k += 1;
}
}

return ans;
}
}

LeetCode 895. Maximum Frequency Stack

Problem Statement


use std::collections::HashMap;
use std::cmp;

struct FreqStack {
mx_freq: i32,
freq: HashMap<i32, i32>,
m: HashMap<i32, Vec<i32>>
}

impl FreqStack {

fn new() -> Self {
FreqStack {
mx_freq: 0,
freq: HashMap::new(),
m: HashMap::new()
}
}

fn push(&mut self, x: i32) {
self.freq.entry(x).or_insert(0);
*self.freq.get_mut(&x).unwrap() += 1;
let val = *self.freq.get(&x).unwrap();
self.mx_freq = cmp::max(self.mx_freq, val);
self.m.entry(val).or_insert(vec![]);
self.m.get_mut(&val).unwrap().push(x);
}

fn pop(&mut self) -> i32 {
let x = self.m.get(&self.mx_freq).unwrap().last().unwrap().clone();
self.m.get_mut(&self.mx_freq).unwrap().pop();
let val = self.freq.get(&x).unwrap();
if !self.m.contains_key(val) || self.m.get(val).unwrap().is_empty() {
self.mx_freq -= 1;
}
*self.freq.get_mut(&x).unwrap() -= 1;
return x;
}
}