【LeetCode】 哈希集 - 用法 C++
2021/7/8 20:15:03
本文主要是介绍【LeetCode】 哈希集 - 用法 C++,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
原来C++有已经写好的哈希集合, 柳神曾经提到过可以过超时的unordered_set 支持 auto迭代器 可以 insert count erase size clear empty#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; } };
这篇关于【LeetCode】 哈希集 - 用法 C++的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-28pyqt 怎么打包整个项目-icode9专业技术文章分享
- 2024-09-28laravel Commands 创建带有参数的 Artisan 命令的步骤和示例-icode9专业技术文章分享
- 2024-09-28antd怎么实现渲染tiff图片-icode9专业技术文章分享
- 2024-09-28英文半角中划线和中文全角的中划线有什么区别-icode9专业技术文章分享
- 2024-09-28nvm npm 和node 他们之间有什么关系-icode9专业技术文章分享
- 2024-09-28Node Version Manager (nvm)使用教程-icode9专业技术文章分享
- 2024-09-28nvm命令太慢,是什么原因-icode9专业技术文章分享
- 2024-09-28Kotlin 如何增加、删除和修改 MutableStateFlow 中的值。-icode9专业技术文章分享
- 2024-09-28Kotlin的stateFlow.update 写法介绍-icode9专业技术文章分享
- 2024-09-28kotlin 怎么获取当前时间格式-icode9专业技术文章分享