-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add problem 1331: Rank Transform of an Array
- Loading branch information
Showing
3 changed files
with
61 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>(); | ||
} | ||
} |