首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >【LeetCode】 哈希集 - 用法 C++

【LeetCode】 哈希集 - 用法 C++

作者头像
韩旭051
发布2020-06-23 11:22:55
发布2020-06-23 11:22:55
1.7K0
举报
文章被收录于专栏:刷题笔记刷题笔记

原来C++有已经写好的哈希集合,

柳神曾经提到过可以过超时的unordered_set

支持 auto迭代器

可以

insert

count

erase

size

clear

empty

代码语言:javascript
复制
#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;
    }
}

https://leetcode-cn.com/explore/learn/card/hash-table/204/practical-application-hash-set/805/配套题目

存在重复元素

给定一个整数数组,判断是否存在重复元素。

如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。

示例 1:

代码语言:javascript
复制
输入: [1,2,3,1]
输出: true

示例 2:

代码语言:javascript
复制
输入: [1,2,3,4]
输出: false

示例 3:

代码语言:javascript
复制
输入: [1,1,1,3,3,4,3,2,4,2]
输出: true
代码语言:javascript
复制
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;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/12/14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档