#include <unordered_set> // 0. include the library int main() { // 1. initialize a hash set unordered_set<int> hashset; // 2. insert a new key hashset.insert(3); hashset.insert(2); hashset.insert(1); // 3. delete a key hashset.erase(2); // 4. check if the key is in the hash set if (hashset.count(2) <= 0) { cout << "Key 2 is not in the hash set." << endl; } // 5. get the size of the hash set cout << "The size of hash set is: " << hashset.size() << endl; // 6. iterate the hash set for (auto it = hashset.begin(); it != hashset.end(); ++it) { cout << (*it) << " "; } cout << "are in the hash set." << endl; // 7. clear the hash set hashset.clear(); // 8. check if the hash set is empty if (hashset.empty()) { cout << "hash set is empty now!" << endl; } }
存在重复元素
给定一个整数数组,判断是否存在重复元素。
如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。
示例 1:
输入: [1,2,3,1] 输出: true
示例 2:
输入: [1,2,3,4] 输出: false
示例 3:
输入: [1,1,1,3,3,4,3,2,4,2] 输出: true
class Solution { public: bool containsDuplicate(vector<int>& nums) { unordered_set<int> s; for(int i=0;i<nums.size();i++){ if(s.count(nums[i])>0){ return true; }s.insert(nums[i]); }return false; } };