[Leetcode] 706. 디자인-해시 맵 (시뮬레이션) [단순]

링크

https://leetcode-cn.com/problems/design-hashmap/

시간 소모적

문제 해결 : 13 분
문제 해결 : 8 분

표제

내장 된 해시 테이블 라이브러리를 사용하지 않고 해시 맵 (HashMap)을 디자인합니다.

MyHashMap 클래스를 구현하십시오.

  • MyHashMap ()은 빈지도로 객체를 초기화합니다.
  • void put (int key, int value) 키-값 쌍 (키, 값)을 HashMap에 삽입합니다. 키가 이미 맵에있는 경우 해당 값 값을 업데이트하십시오.
  • int get (int key) 특정 키로 매핑 된 값을 반환합니다. 매핑에 키 매핑이 포함되어 있지 않으면 -1을 반환합니다.
  • void remove (key) 매핑에 키 매핑이있는 경우 키와 해당 값을 제거합니다.

신속한:

  • 0 <= 키, 값 <= 10 6 10 ^ 61 06
  • 10 4 10 ^ 4 까지 전화1 04 put, get, remove 메소드

아이디어

체인 주소 방법 : 해시 함수 x % base, put () 먼저 해시 값의 연결 목록에서 검색하고, 업데이트 된 값을 찾고, 찾을 수없는 경우 쌍을 추가합니다. 해시 값의 연결 목록에서 get () 검색을 수행합니다. find it 반환 값, 그렇지 않으면 -1 반환; remove ()는 해시 값의 링크 된 목록을 찾고 발견되면이 위치에서 요소 쌍을 삭제하고 직접 반환합니다.

시간 복잡도 : O (n / b) O (n / b)O ( n / b ) 균등 분포 가정, n 데이터, b 연결 목록에 데이터가 있음

AC 코드

class MyHashMap {
    
    
private:
    vector<list<pair<int, int>>> data;
    int base = 769;                                    
public:
    int hash(int x) {
    
    
        return x % base;
    }                              
                                        
    /** Initialize your data structure here. */
    MyHashMap() {
    
    
        data.resize(base);
    }
    
    /** value will always be non-negative. */
    void put(int key, int value) {
    
    
        int h = hash(key);
        for(auto it = data[h].begin(); it != data[h].end(); ++it) {
    
    
            if(it->first == key) {
    
    
                it->second = value;
                return ;
            }
        }
        data[h].push_back(make_pair(key, value));
    }
    
    /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
    int get(int key) {
    
    
        int h = hash(key);
        for(auto x : data[h]) {
    
    
            if(x.first == key) return x.second;      
        }
        return -1;
    }
    
    /** Removes the mapping of the specified value key if this map contains a mapping for the key */
    void remove(int key) {
    
    
        int h = hash(key);
        for(auto it = data[h].begin(); it != data[h].end(); ++it) {
    
    
            if(it->first == key) {
    
    
                data[h].erase(it);
                return ;
            }
        }
    }
};

/**
 * Your MyHashMap object will be instantiated and called as such:
 * MyHashMap* obj = new MyHashMap();
 * obj->put(key,value);
 * int param_2 = obj->get(key);
 * obj->remove(key);
 */

추천

출처blog.csdn.net/Krone_/article/details/114784696