[LeetCode] Divide Array Into Equal Pairs

2206. Divide Array Into Equal Pairs

You are given an integer array nums consisting of 2 * n integers.

You need to divide nums into n pairs such that:

  • Each element belongs to exactly one pair.
  • The elements present in a pair are equal.
    Return true if nums can be divided into n pairs, otherwise return false.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
bool divideArray(vector<int>& nums) {
int n = nums.size();
if(n & 1) return false;
unordered_set<int> s;
for(int n : nums) {
if(s.count(n)) s.erase(n);
else s.insert(n);
}
return s.size() == 0;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/20/PS/LeetCode/divide-array-into-equal-pairs/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.