In a deck of cards, each card has an integer written on it.
Return true
if and only if you can choose X >= 2
such that it is possible to split the entire deck into 1 or more groups of cards, where:
- Each group has exactly
X
cards. - All the cards in each group have the same integer.
Input: [1,2,3,4,4,3,2,1] Output: true Explanation: Possible partition [1,1],[2,2],[3,3],[4,4]
Input: [1,1,1,2,2,2,3,3] Output: false Explanation: No possible partition.
Input: [1] Output: false Explanation: No possible partition.
Input: [1,1] Output: true Explanation: Possible partition [1,1]
Input: [1,1,2,2,2,2] Output: true Explanation: Possible partition [1,1],[2,2],[2,2]
1 <= deck.length <= 10000
0 <= deck[i] < 10000
use std::collections::HashMap;
impl Solution {
pub fn has_groups_size_x(deck: Vec<i32>) -> bool {
let mut map = HashMap::new();
for n in &deck {
*map.entry(n).or_insert(0) += 1;
}
for x in (2..=(deck.len() / map.len())).filter(|x| deck.len() % x == 0) {
if map.values().all(|v| v % x == 0) {
return true;
}
}
false
}
}
use std::collections::HashMap;
impl Solution {
pub fn has_groups_size_x(deck: Vec<i32>) -> bool {
let mut map = HashMap::new();
for n in deck {
*map.entry(n).or_insert(0) += 1;
}
let mut x = *map.values().nth(0).unwrap();
map.values().fold(x, |x, y| Self::gcd(x, *y)) > 1
}
pub fn gcd(mut x: i32, mut y: i32) -> i32 {
while x % y != 0 {
let tmp = x;
x = y;
y = tmp % y;
}
y
}
}