Skip to content

Commit 1c257ba

Browse files
committed
Add problem 2610: Convert an Array Into a 2D Array With Conditions
1 parent bfd1596 commit 1c257ba

3 files changed

Lines changed: 78 additions & 0 deletions

File tree

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1927,6 +1927,7 @@ pub mod problem_2600_k_items_with_the_maximum_sum;
19271927
pub mod problem_2601_prime_subtraction_operation;
19281928
pub mod problem_2602_minimum_operations_to_make_all_array_elements_equal;
19291929
pub mod problem_2609_find_the_longest_balanced_substring_of_a_binary_string;
1930+
pub mod problem_2610_convert_an_array_into_a_2d_array_with_conditions;
19301931

19311932
#[cfg(test)]
19321933
mod test_utilities;
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
pub fn find_matrix(nums: Vec<i32>) -> Vec<Vec<i32>> {
7+
let mut counts = vec![0_u8; nums.len()].into_boxed_slice();
8+
let mut result = Vec::<Vec<_>>::new();
9+
10+
for num in nums {
11+
let count = &mut counts[num as u32 as usize - 1];
12+
let old_count = *count;
13+
14+
*count += 1;
15+
16+
if let Some(row) = result.get_mut(usize::from(old_count)) {
17+
row.push(num);
18+
} else {
19+
result.push(vec![num]);
20+
}
21+
}
22+
23+
result
24+
}
25+
}
26+
27+
// ------------------------------------------------------ snip ------------------------------------------------------ //
28+
29+
impl super::Solution for Solution {
30+
fn find_matrix(nums: Vec<i32>) -> Vec<Vec<i32>> {
31+
Self::find_matrix(nums)
32+
}
33+
}
34+
35+
#[cfg(test)]
36+
mod tests {
37+
#[test]
38+
fn test_solution() {
39+
super::super::tests::run::<super::Solution>();
40+
}
41+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
pub mod greedy;
2+
3+
pub trait Solution {
4+
fn find_matrix(nums: Vec<i32>) -> Vec<Vec<i32>>;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
use crate::test_utilities;
11+
use std::collections::HashSet;
12+
13+
pub fn run<S: Solution>() {
14+
let test_cases = [(&[1, 3, 4, 1, 2, 3, 1] as &[_], 3), (&[1, 2, 3, 4], 1)];
15+
let mut buffer = HashSet::new();
16+
17+
for (nums, expected) in test_cases {
18+
let result = S::find_matrix(nums.to_vec());
19+
20+
assert_eq!(
21+
test_utilities::unstable_sorted(result.iter().flatten().copied()),
22+
test_utilities::unstable_sorted(nums.iter().copied()),
23+
);
24+
25+
for row in &result {
26+
buffer.extend(row.iter().copied());
27+
28+
assert_eq!(row.len(), buffer.len());
29+
30+
buffer.clear();
31+
}
32+
33+
assert_eq!(result.len(), expected);
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)