使用哈希集查重
/*
* Template for using hash set to find duplicates.
*/
bool findDuplicates(vector<Type>& keys) {
// Replace Type with actual type of your key
unordered_set<Type> hashset;
//C++11 for循环新写法
for (Type key : keys) {
if (hashset.count(key) > 0) {
return true;
}
hashset.insert(key);
}
return false;
}
存在重复元素
题目:
题解:
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
//使用哈希集判断
unordered_set<int> hashset;
for(int num:nums){
if(hashset.count(num)>0){
//该元素已存在
return true;
}
hashset.insert(num);
}
return false;
}
};
只出现一次的数字
题解:
class Solution {
public:
int singleNumber(vector<int>& nums) {
//使用哈希集判断
unordered_set<int> hashset;
for(int num:nums){
if(hashset.count(num)>0){
//该元素已存在
//删除
hashset.erase(num);
}else{
//不存在 加入
hashset.insert(num);
}
}
//哈希集合中只有出现一次的元素 返回即可
return *(hashset.begin());
}
};
两个数组的交集
题解:
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
//返回vector
vector<int> result;
//哈希集
unordered_set<int> hashset;
//遍历一个vector将值加入哈希集中
for(int num:nums1){
//没有必要用if语句判断 insert之前它会判断是否存在
hashset.insert(num);
}
//遍历另一个vector
for(int num:nums2){
if(hashset.count(num)>0){
//存在 交集元素之一
result.push_back(num);
//在哈希表中删除元素 这样重复元素就不会被重复加入
hashset.erase(num);
}
}
return result;
}
};
快乐数
题解:
class Solution {
public:
bool isHappy(int n) {
//哈希集
unordered_set<int> hashset;
int m = n;
while(m!=1){
hashset.insert(m);
int sum = 0;
while(m!=0){
sum += pow(m%10,2);
m = m/10;
}
//将和又赋值给m
m = sum;
//如果得到的数跟之前的重复 就一定不是快乐数
if(hashset.find(m)!=hashset.end()){
//找到了 重复
return false;
}
}
//除了循环说明m(sum)为1
return true;
}
};