哈希堆的实现

来源:互联网 发布:域名怎么和服务器绑定 编辑:程序博客网 时间:2024/06/16 17:03

hash堆额主要用途在于滑动窗口找最值

// 传入函数为myless 为 小堆 默认为小堆bool myless(int x, int y) {    return x < y;}// 大堆bool mygreater(int x, int y) {    return x > y;}// hash堆class HashHeap{private:    vector<int> array;    bool (*compatator)(int x, int y);    unordered_map<int,int> hashmap;    void heapUp(int i) {        int x =array[i];        while (i > 0) {            int p = (i - 1) / 2;            if(!compatator(array[p],x)) {                break;            }            array[i] = array[p];            hashmap[array[p]] = i;            i = p;        }        array[i] = x;        hashmap[x] = i;    }    void heapDown(int i) {        int x = array[i];        while (2 * i + 1 < array.size()) {            int min = 2 * i + 1;            int max = 2 * i + 2;            if(max < array.size() && compatator(array[max],array[min])) {                min = max;            }            if(compatator(x,array[min])) {                break;            }            array[i] = array[min];            hashmap[array[min]] = i;            i = min;        }        array[i] = x;        hashmap[x] = i;    }    void initial() {        int end = (array.size() & 0x1) ? (array.size()) / 2 - 1: (array.size()-1) / 2;        for (int i = end; i >= 0 ; --i) {            heapDown(i);        }        for (int j = 0; j < array.size(); ++j) {            hashmap.insert(make_pair(array[j],j));        }    }public:    HashHeap(vector<int>& another, bool (*compatator)(int x, int y) = myless) :array(another),compatator(compatator) {            initial();    }    void push(int x) {        array.push_back(x);        hashmap.insert(make_pair(x,array.size() -1));        heapUp(array.size() - 1);    }    int pop() {        if(array.size() > 0) {            int x = array[0];            swap(array[0],array[array.size() - 1]);            hashmap.erase(x);            array.pop_back();            heapDown(0);            return x;        } else{            return -1;        }    }    void deleteElement(int key) {        int idx = hashmap[key];        swap(array[array.size() - 1], array[idx]);        for (unordered_map<int,int>::iterator it = hashmap.begin(); it != hashmap.end() ; ++it) {            if(it->first == key) {                hashmap.erase(it);                break;            }        }        hashmap[array[idx]] = idx;        array.pop_back();        heapDown(idx);    }};
原创粉丝点击