2206: Divide-Array-Into-Equal-Pairs
Easy
table of contents
Just create a map, count, to maintain the count
of every num in nums. Then, when interating
through nums, just xor
count[num] with 1 and then increment /
decrement unpaired_count depending on if
count[num] is equal to 1 or
0.
Finally, if unpaired_count > 0, then we know
nums cannot be divided into n pairs.
code
class Solution {
public:
bool divideArray(vector<int>& nums) {
int count[501] = {0};
int unpaired_count = 0;
for (int num : nums) {
count[num] ^= 1;
if (count[num]) {
++unpaired_count;
} else {
--unpaired_count;
}
}
return (unpaired_count) ? false : true;
}
};