Skip to content

Commit

Permalink
Add problem 2148: Count Elements With Strictly Smaller and Greater El…
Browse files Browse the repository at this point in the history
…ements
  • Loading branch information
EFanZh committed Feb 24, 2024
1 parent 7e72436 commit 15f567d
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1458,6 +1458,7 @@ pub mod problem_2134_minimum_swaps_to_group_all_1s_together_ii;
pub mod problem_2138_divide_a_string_into_groups_of_size_k;
pub mod problem_2140_solving_questions_with_brainpower;
pub mod problem_2144_minimum_cost_of_buying_candies_with_discount;
pub mod problem_2148_count_elements_with_strictly_smaller_and_greater_elements;

#[cfg(test)]
mod test_utilities;
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

use std::cmp::Ordering;

impl Solution {
pub fn count_elements(nums: Vec<i32>) -> i32 {
let mut iter = nums.iter().copied();
let mut min = iter.next().unwrap();
let mut min_count = 1;
let mut max = min;
let mut max_count = 1;

for num in iter {
match num.cmp(&min) {
Ordering::Less => {
min = num;
min_count = 1;
}
Ordering::Equal => min_count += 1,
Ordering::Greater => {}
}

match num.cmp(&max) {
Ordering::Less => {}
Ordering::Equal => max_count += 1,
Ordering::Greater => {
max = num;
max_count = 1;
}
}
}

if min == max {
0
} else {
nums.len() as i32 - min_count - max_count
}
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn count_elements(nums: Vec<i32>) -> i32 {
Self::count_elements(nums)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
pub mod iterative;

pub trait Solution {
fn count_elements(nums: Vec<i32>) -> i32;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
let test_cases = [
(&[11, 7, 2, 15] as &[_], 2),
(&[-3, 3, 3, 90], 2),
(&[0], 0),
(&[-71, -71, 93, -71, 40], 1),
];

for (nums, expected) in test_cases {
assert_eq!(S::count_elements(nums.to_vec()), expected);
}
}
}

0 comments on commit 15f567d

Please sign in to comment.