Skip to content

Commit

Permalink
Add problem 1365: How Many Numbers Are Smaller Than the Current Number
Browse files Browse the repository at this point in the history
  • Loading branch information
Spxg committed Dec 22, 2024
1 parent 2144295 commit b34c649
Show file tree
Hide file tree
Showing 3 changed files with 63 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 @@ -546,6 +546,7 @@ pub mod problem_1338_reduce_array_size_to_the_half;
pub mod problem_1344_angle_between_hands_of_a_clock;
pub mod problem_1346_check_if_n_and_its_double_exist;
pub mod problem_1357_apply_discount_every_n_orders;
pub mod problem_1365_how_many_numbers_are_smaller_than_the_current_number;
pub mod problem_1375_number_of_times_binary_string_is_prefix_aligned;
pub mod problem_1381_design_a_stack_with_increment_operation;
pub mod problem_1387_sort_integers_by_the_power_value;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
pub struct Solution;

use std::{
cmp::Reverse,
collections::{BinaryHeap, HashMap},
};

impl Solution {
pub fn smaller_numbers_than_current(nums: Vec<i32>) -> Vec<i32> {
let mut result = vec![0; nums.len()];
let mut map = HashMap::with_capacity(nums.len());
let mut heap: BinaryHeap<Reverse<_>> =
nums.into_iter().zip(0usize..).map(Reverse).collect();

let mut count = 0;
while let Some(Reverse((val, idx))) = heap.pop() {
if let Some(x) = map.insert(val, idx) {
result[idx] = result[x];
} else {
result[idx] = count;
}
count += 1;
}
result
}
}

impl super::Solution for Solution {
fn smaller_numbers_than_current(nums: Vec<i32>) -> Vec<i32> {
Self::smaller_numbers_than_current(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,22 @@
pub mod heap;

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

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

pub fn run<S: Solution>() {
let test_cases = [
(&[8, 1, 2, 2, 3] as &[_], &[4, 0, 1, 1, 3] as &[_]),
(&[6, 5, 4, 8], &[2, 1, 0, 3]),
(&[7, 7, 7, 7], &[0, 0, 0, 0]),
];

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

0 comments on commit b34c649

Please sign in to comment.