1146. Snapshot Array

Question Discribtion

Implement a SnapshotArray that supports the following interface:

SnapshotArray(int length) initializes an array-like data structure with the given length. Initially, each element equals 0.
void set(index, val) sets the element at the given index to be equal to val.
int snap() takes a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1.
int get(index, snap_id) returns the value at the given index, at the time we took the snapshot with the given snap_id

#include<map>
#include<vector>
class SnapshotArray {
public:
    SnapshotArray(int length) {
        snapCnt = 0;
        map<int,int> t;
        t[0] = 0;
        
        for(int i = 0;i < length; ++i){
            arr.push_back(t);
        }
    }
    
    void set(int index, int val) {
        arr[index][snapCnt] = val;
    }
    
    int snap() {
        snapCnt++;
        return snapCnt-1;
    }
    
    int get(int index, int snap_id) {
       auto it = arr[index].upper_bound(snap_id);
       it--;
       return arr[index][it->first];
    }
private:
    vector<map<int,int>> arr;
    int snapCnt;
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容