Skip to content

Commit

Permalink
Add problem 1331: Rank Transform of an Array
Browse files Browse the repository at this point in the history
  • Loading branch information
Spxg committed Dec 23, 2024
1 parent 3bd5488 commit 70212eb
Show file tree
Hide file tree
Showing 3 changed files with 61 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 @@ -541,6 +541,7 @@ pub mod problem_1317_convert_integer_to_the_sum_of_two_no_zero_integers;
pub mod problem_1323_maximum_69_number;
pub mod problem_1324_print_words_vertically;
pub mod problem_1325_delete_leaves_with_a_given_value;
pub mod problem_1331_rank_transform_of_an_array;
pub mod problem_1333_filter_restaurants_by_vegan_friendly_price_and_distance;
pub mod problem_1338_reduce_array_size_to_the_half;
pub mod problem_1344_angle_between_hands_of_a_clock;
Expand Down
25 changes: 25 additions & 0 deletions src/problem_1331_rank_transform_of_an_array/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
pub mod sort;

pub trait Solution {
fn array_rank_transform(arr: Vec<i32>) -> Vec<i32>;
}

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

pub fn run<S: Solution>() {
let test_cases = [
(&[40, 10, 20, 30] as &[_], &[4, 1, 2, 3] as &[_]),
(&[100, 100, 100], &[1, 1, 1]),
(
&[37, 12, 28, 9, 100, 56, 80, 5, 12],
&[5, 3, 4, 2, 8, 6, 7, 1, 3],
),
];

for (arr, expected) in test_cases {
assert_eq!(S::array_rank_transform(arr.to_vec()), expected);
}
}
}
35 changes: 35 additions & 0 deletions src/problem_1331_rank_transform_of_an_array/sort.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
pub struct Solution;

impl Solution {
pub fn array_rank_transform(arr: Vec<i32>) -> Vec<i32> {
let mut result = vec![0; arr.len()];
let mut nums: Vec<_> = arr.into_iter().zip(0usize..).collect();
nums.sort_unstable();
let mut prev = None;
let mut count = 1;
for (num, idx) in nums {
if let Some(val) = prev {
if val != num {
count += 1;
}
}
result[idx] = count;
prev = Some(num);
}
result
}
}

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

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}

0 comments on commit 70212eb

Please sign in to comment.