티스토리 뷰

leetcode.com/problems/design-hashset/

 

Design HashSet - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Hash table관련 라이브러리 사용없이 Hash Set 형태의 클래스를 만들라고 한다.

class MyHashSet {
public:
    list<int> set;
    MyHashSet() {}

    void add(int key) {
        set.push_back(key);
    }

    void remove(int key) {
        set.remove(key);
    }

    bool contains(int key) {
        for (list<int>::iterator it = set.begin(); it != set.end(); it++) {
            if (*it == key) return true;
        }
        return false;
    }
};

 

 간단하게 list사용해서 만듬

원래 key값이 충돌되면 안되지만 충돌이 나면 어떻게 하라는게 없어서 걍 따로 추가는 안한 코드이다.

만약 충돌에 대한 처리를 한다면 아래의 코드가 되겠다.

class MyHashSet {
public:
    list<int> set;
    MyHashSet() {}

    void add(int key) {
        if (contains(key) == false) set.push_back(key);
        else throw "existed key";
    }

    //remove key
    void remove(int key) {
        set.remove(key);
    }

    bool contains(int key) {
        for (list<int>::iterator it = set.begin(); it != set.end(); it++) {
            if (*it == key) return true;
        }
        return false;
    }
    ~MyHashSet() {
        set.clear();
    }
};

add할때 이미 key가 존재한다면 강제로 오류내버린다.

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함