xor Intersection of Two Arrays [Happy Number] (https://leetcode.com/explore/learn/card/hash-table/183/combination-with-other-algorithms/1131/)

1
2
3
4
5
6
7
8
9
10
class  {
public:
int singleNumber (vector<int>& nums) {
int result = 0;
for (int num : nums) {
result ^= num;
}
return result;
}
};

A better explanation why this technique works-

Let’s say we have an array - [2,1,4,5,2,4,1].
What we are doing is essentially this-

=> 0 ^ 2 ^ 1 ^ 4 ^ 5 ^ 2 ^ 4 ^ 1

=> 0^ 2^2 ^ 1^1 ^ 4^4 ^5 (Rearranging, taking same numbers together)

=> 0 ^ 0 ^ 0 ^ 0 ^ 5

=> 0 ^ 5

=> 5 🙂

Intersection of Two Arrays

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class  {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> myset(nums1.begin(), nums1.end());
vector<int> result;
for (int num2 : nums2) {
if (myset.count(num2) > 0) {
result.push_back(num2);
myset.erase(num2);
}
}
return result;
}
};

使用迭代器初始化set

从关联容器删除元素

c.erase(k) 从c中删除每个关键字为k的元素。返回一个size_type值,指出删除元素的数量

[Happy Number] (https://leetcode.com/explore/learn/card/hash-table/183/combination-with-other-algorithms/1131/)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class  {
public:
unordered_map<int, int> path;
bool isHappy(int n) {
int value=0;
int key=n;
while (n) {//calculate the value of the key.
int temp = n%10;
value+=temp*temp;
n/=10;
}
if (value==1) {//if the value is 1,the key is a happy number.
return true;
}
if (path.count(value) > 0) {//if the value is already in the map,there is a cycle,so the key is not a happy number.
return false;
}
path[key]=value;//put the key/value in the map
return isHappy(value);//calculate recursively
}
};