본문 바로가기

Algorithm/자료구조

(C++) - LeetCode (easy) 705. Design HashSet

반응형

https://leetcode.com/problems/design-hashset/description/

 

Design HashSet - LeetCode

Can you solve this real interview question? Design HashSet - Design a HashSet without using any built-in hash table libraries. Implement MyHashSet class: * void add(key) Inserts the value key into the HashSet. * bool contains(key) Returns whether the value

leetcode.com

class를 구현해보는 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

set을 member 변수로 선언해줍니다.

📔 풀이과정

set에 구현되어 있는 기본 내장함수로 해당 class들을 적절히 구현할 수 있습니다. contains함수의 경우 find함수를 이용해 iter의 end()가 아니라면 해당 key를 찾은 셈이 됩니다.


📕 Code

📔 C++

class MyHashSet {
    set <int> s;
public:
    MyHashSet() {
    }
    
    void add(int key) {
        s.insert(key);
    }
    
    void remove(int key) {
        s.erase(key);
    }
    
    bool contains(int key) {
        return s.find(key) != s.end();
    }
};

/**
 * Your MyHashSet object will be instantiated and called as such:
 * MyHashSet* obj = new MyHashSet();
 * obj->add(key);
 * obj->remove(key);
 * bool param_3 = obj->contains(key);
 */

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.