LeetCode - 705. Design HashSet(Array, Hash Table, Linked List, Design, Hash Function)*

YAMAMAMO·2022년 4월 4일
0

LeetCode

목록 보기
47/100

문제

내장된 해시 테이블 라이브러리를 사용하지 않고 HashSet을 설계합니다.
MyHashSet 클래스 구현:
void add(key) 값 키를 HashSet에 삽입합니다.
bool contains (key) 값 키가 HashSet에 있는지 여부를 반환합니다.
void remove(key) 해시 집합에서 값 키를 제거합니다. HashSet에 키가 존재하지 않으면 아무것도 하지 마십시오.

https://leetcode.com/problems/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 key exists in the HashSet or not.
void remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing.

Example 1:

Input
{"MyHashSet", "add", "add", "contains", "contains", "add", "contains", "remove", "contains"}
{ [], [1], [2], [1], [3], [2], [2], [2], [2] }
[null, null, null, true, false, null, true, null, false]
Explanation
MyHashSet myHashSet = new MyHashSet();
myHashSet.add(1); // set = [1]
myHashSet.add(2); // set = [1, 2]
myHashSet.contains(1); // return True
myHashSet.contains(3); // return False, (not found)
myHashSet.add(2); // set = [1, 2]
myHashSet.contains(2); // return True
myHashSet.remove(2); // set = [1]
myHashSet.contains(2); // return False, (already removed)

풀이

자바입니다.

  • HashSet은 중복되는 값이 저장되지 않습니다.
  • ArrayList를 사용해서 풀었습니다.
class MyHashSet {
    List<Integer> contain;

    public MyHashSet() {
        contain = new ArrayList();
    }
    
    public void add(int key) {
        if(!contains(key)){
            contain.add(key);    
        }else return;
    }
    
    public void remove(int key) {
        int index = contain.indexOf(key);
        if(index!=-1) contain.remove(index);
    }
    
    //데이터가 있는지 유무 파악
    public boolean contains(int key) {
        return contain.contains(key);
    }
}

/**
 * Your MyHashSet object will be instantiated and called as such:
 * MyHashSet obj = new MyHashSet();
 * obj.add(key);
 * obj.remove(key);
 * boolean param_3 = obj.contains(key);
 */
profile
안드로이드 개발자

0개의 댓글