매일 매일 성장하는 섭섭군

[Leet Coding Challenge] Design HashSet, 2020.08.01~07 본문

알고리즘 문제풀이/LeetCode

[Leet Coding Challenge] Design HashSet, 2020.08.01~07

섭섭군 2020. 8. 3. 14:41
반응형

 

영어공부도 할겸 알고리즘 문제를 LeetCode 에서도 풀어보기로 했다. 

그 중 Leet Coding Challenge라는 것이 있어 매주 도전하면 좋을것 같다는 생각이 든다. 

 

처음 풀어본 문제는 다소 쉬운 문제다. 해시를 구현하는 것인데 백준이나 프로그래머스 등에서 해시를 사용하여  문제를 푸는 것이 아닌 그냥

해시를 구현하라! 라는 문제이다. 문제는 다음과 같다. 

 

leetcode.com/explore/featured/card/august-leetcoding-challenge/549/week-1-august-1st-august-7th/3410/

 

Explore - LeetCode

LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.

leetcode.com

 

해시에 값을 추가하거나 삭제, 해당 값이 존재하는지를 살피면 된다.

전체 풀이 코드는 다음과 같다. 

class MyHashSet:

    def __init__(self):
        self.myDict = [False]*1000001
        

    def add(self, key: int) -> None:
        self.myDict[key] = True
        

    def remove(self, key: int) -> None:
        if self.contains(key) :
            self.myDict[key] = False
        

    def contains(self, key: int) -> bool:
        return self.myDict[key]

 

 

ps) 문제 조건에 hash-set 라이브러리를 사용하지 말라고 했는데 사용해도 통과되긴 한다. 다음은 라이브러리를 사용했을 때이다.(dict 사용)

class MyHashSet:

    def __init__(self):
        self.myDict = dict()
        

    def add(self, key: int) -> None:
        self.myDict[key] = True
        

    def remove(self, key: int) -> None:
        if self.contains(key) :
            del self.myDict[key]
        

    def contains(self, key: int) -> bool:
        if key in self.myDict :
            return True
        else :
            return False
반응형
Comments