|
| 1 | +/** |
| 2 | + * [1282] group the people given the group size they belong to |
| 3 | + * https://leetcode.cn/problems/group-the-people-given-the-group-size-they-belong-to/ |
| 4 | + */ |
| 5 | +use std::collections::HashMap; |
| 6 | + |
| 7 | +pub struct Solution {} |
| 8 | + |
| 9 | +impl Solution { |
| 10 | + pub fn group_the_people(group_sizes: Vec<i32>) -> Vec<Vec<i32>> { |
| 11 | + let mut people_size_map: HashMap<i32, Vec<i32>> = HashMap::new(); |
| 12 | + for (index, size) in group_sizes.iter().enumerate() { |
| 13 | + let index = index as i32; |
| 14 | + match people_size_map.get_mut(size) { |
| 15 | + None => { |
| 16 | + let people = Vec::from([index]); |
| 17 | + people_size_map.insert(*size, people); |
| 18 | + } |
| 19 | + Some(arr) => arr.push(index as i32), |
| 20 | + } |
| 21 | + } |
| 22 | + println!("{:?}", people_size_map); |
| 23 | + let mut groups: Vec<Vec<i32>> = Vec::new(); |
| 24 | + for (size, people) in people_size_map { |
| 25 | + let groups_for_size: Vec<&[i32]> = people.chunks(size as usize).collect(); |
| 26 | + groups_for_size |
| 27 | + .iter() |
| 28 | + .for_each(|v| groups.push((**v).to_vec())); |
| 29 | + |
| 30 | + // let group_count = people.len() as i32 / size; |
| 31 | + // for g in 0..group_count { |
| 32 | + // let mut group = Vec::new(); |
| 33 | + // let mut start = g * size; |
| 34 | + // for j in 0..size { |
| 35 | + // let index = (start + j) as usize; |
| 36 | + // group.push(people[index]); |
| 37 | + // } |
| 38 | + // groups.push(group); |
| 39 | + // } |
| 40 | + } |
| 41 | + |
| 42 | + groups |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +#[cfg(test)] |
| 47 | +mod tests { |
| 48 | + use super::*; |
| 49 | + |
| 50 | + #[test] |
| 51 | + fn test_1282() { |
| 52 | + assert_eq!( |
| 53 | + Solution::group_the_people(vec![3, 3, 3, 3, 3, 1, 3]), |
| 54 | + vec![vec![5], vec![0, 1, 2], vec![3, 4, 6]] |
| 55 | + ); |
| 56 | + } |
| 57 | +} |
0 commit comments