-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2206.cpp
More file actions
65 lines (52 loc) · 1.07 KB
/
2206.cpp
File metadata and controls
65 lines (52 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/* Approach 1: Using Map
TC: O(n)
SC: O(n)
*/
class Solution {
public:
bool divideArray(vector<int>& nums) {
unordered_map<int, int> mp;
bool canDivided = true;
for(auto& e: nums)
{
mp[e]++;
}
for(auto& e: nums)
{
if(mp[e]%2 != 0)
return canDivided = false;
}
return canDivided;
}
};
/* Approach 2: Using Sort
TC: O(nlogn)
SC: O(logn)
*/
class Solution {
public:
bool divideArray(vector<int>& nums) {
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); i += 2) {
if (nums[i] != nums[i + 1]) {
return false;
}
}
return true;
}
};
/* Approach 3: using XOR
TC: O(n)
SC: O(1)
*/
class Solution {
public boolean divideArray(int[] nums) {
int len = nums.length;
int xor1=0, xor2=0;
for(int i=0;i<len;i++){
xor1 = nums[i]^xor1;
xor2 = (nums[i]+1)^xor2;
}
return xor1==0 && xor2==0;
}
}