【面試題】實現一個數據結構,要求 set(index, val)、get(index)、setAll(val)三種操作時間複雜度都是O(1)

想了好久。。。

代碼

class Node{
private:
    map<int, pair<int, int> > mp; // index, cnt, val
    int tot;
    int cnt = 0;
public:
    void set(int index, int value) {
        mp[index] = {cnt, value};
    }
    int get(int index) {
        int tcnt = mp[index].first;
        int val = mp[index].second;
        if (tcnt == cnt) return val;
        return tot;
    }
    void setAll(int val) {
        cnt++;
        tot = val;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章