首页 > 其他分享 >剑指offer第二版

剑指offer第二版

时间:2023-02-10 10:14:07浏览次数:39  
标签:index return offer int 第二 nums hashtable key

https://leetcode.cn/problems/design-hashset/ 设计hash集合

class MyHashSet {
    constexpr static int size = 700;
    vector<list<int>> hashtable;
    int hash(int key) {
        return key % size;
    }
public:
    MyHashSet():hashtable(size) {

    }

    void add(int key) {
        int index = hash(key);
        for (auto i = hashtable[index].begin(); i != hashtable[index].end(); ++i) {
            if (*i == key) {
                return;
            }
        }
        hashtable[index].push_back(key);

    }

    void remove(int key) {
        int index = hash(key);
        for (auto i = hashtable[index].begin(); i != hashtable[index].end(); ++i) {
            if (*i == key) {
                hashtable[index].erase(i);
                return;
            }
        }
    }

    bool contains(int key) {
        int index = hash(key);
        for (auto i = hashtable[index].begin(); i != hashtable[index].end(); ++i) {
            if (*i == key) {
                return true;
            }
        }
        return false;
    }
};
View Code

 剑指 Offer 03. 数组中重复的数字

class Solution {
public:
    int findRepeatNumber(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        for (int i = 1; i < nums.size(); ++i) {
            if (nums[i] == nums[i - 1]) {
                return nums[i];
            }
        }
        return -1;
    }
};
View Code

 

标签:index,return,offer,int,第二,nums,hashtable,key
From: https://www.cnblogs.com/yanzhao-x/p/17107946.html

相关文章