Input: nums =[1,1,1,1]Output: falseExplanation: The only possible way to split nums is nums1 =[1,1] and nums2 =[1,1]. Both nums1 and nums2 do not contain distinct elements. Therefore, we returnfalse.
If any number appears more than n/2 times, it is impossible to split the array into two groups of n/2 distinct elements each, because that number would have to appear in both groups, violating the distinctness requirement.
classSolution {
publicbooleanisPossibleToSplit(int[] nums) {
Map<Integer, Integer> freq =new HashMap<>();
for (int x : nums) freq.put(x, freq.getOrDefault(x, 0) + 1);
int n = nums.length/ 2;
for (int v : freq.values()) if (v > n) returnfalse;
returntrue;
}
}
1
2
3
4
5
6
7
8
9
classSolution {
funisPossibleToSplit(nums: IntArray): Boolean {
val freq = mutableMapOf<Int, Int>()
for (x in nums) freq[x] = freq.getOrDefault(x, 0) + 1val n = nums.size / 2for (v in freq.values) if (v > n) returnfalsereturntrue }
}
1
2
3
4
5
defisPossibleToSplit(nums: list[int]) -> bool:
from collections import Counter
freq = Counter(nums)
n = len(nums) //2return all(v <= n for v in freq.values())
1
2
3
4
5
6
7
8
9
10
11
use std::collections::HashMap;
impl Solution {
pubfnis_possible_to_split(nums: Vec<i32>) -> bool {
letmut freq = HashMap::new();
for x in nums.iter() {
*freq.entry(*x).or_insert(0) +=1;
}
let n = nums.len() /2;
freq.values().all(|&v| v <= n)
}
}