【11月LeetCode组队打卡】Task1--HashTable

发布时间 2023-11-16 19:08:12作者: Wennz-y

在准备CSP,借这次组队打卡的机会好好复习一下cpp的各种基操(微操,和基础的数据结构

217.存在重复元素

vector

向量的用法有点忘了,先简单回顾一下

(其实是好久没写cpp了(安详.jpg

输入与输出

    //未知数组元素个数
    vector<int> hash;
    int x;

    while(cin>>x){
        hash.push_back(x);
        //遇到回车就停止输入
        if(cin.get()=='\n')
            break;
    }

    for(int num:hash)
        cout<<num<<' ';
    /*
    for(int i=0;i<hash.size();i++)
        cout<<hash[i]<<' ';
    */

插入

    //在下标为2的前面插入666(首下标为0
    hash.insert(hash.begin()+2,666);

删除

    //左闭右开
    hash.erase(hash.begin()+1,hash.begin()+2);

unordered_set

set.find(x)

如果在set中找到x,则返回x的角标(迭代器);

否则返回set末尾迭代器set.end( );

//在s中寻找x
if(s.find(x)!=s.end())
            return true;

AC1--排序:判断相邻元素是否相等

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

bool duplicates(vector<int> &nums){
    sort(nums.begin(),nums.end());
    for(int i=0;i<nums.size()-1;i++){
        if(nums[i]==nums[i+1])
            return true;
    }
    return false;
}

void getArray(vector<int> &array){
    int x;
    while(cin>>x){
        array.push_back(x);
        if(cin.get()=='\n')
            break;
    }
    return;
}

int main()
{
    vector<int>  nums;
    getArray(nums);

    if(duplicates(nums))
        cout<<"Contain Duplicates";
    else    
        cout<<"No Duplicates";
    return 0;
}



AC2--哈希表

两个集合,一个装元素(nums),一个用于查找(s)

nums中挨个元素匹配s:配上=>重复;没配上=>插入s中

//只修改判断功能函数和头文件,其余同AC1
#include<unodered_set>

bool duplicates(vector<int> &nums){
    unordered_set<int> s;
    for(int x:nums){
        if(s.find(x)!=s.end())
            return true;
        s.insert(x);
    }
    return false;
}