xinyu04

导航

[Google] LeetCode 1146 Snapshot Array

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

Solution

对于每一个位置,我们用 \(vector\)\(pair\) 来存储每次记录的 \(snap\_id, val\); 对于查找某个 \(snap\_id\)\(val\),利用二分查找即可。

点击查看代码
class SnapshotArray {
typedef pair<int,int> pii;
private:
    
    int cnt=0;
    vector<vector<pii>> shot;
    
public:
    SnapshotArray(int length) {
        // snap_id, val
        shot = vector<vector<pii>> (length, vector<pii>(1,{0,0}));
        cnt=0;
    }
    
    void set(int index, int val) {
        int sz = shot[index].size();
        if(shot[index][sz-1].first==cnt)
            shot[index][sz-1].second=val;
        else
            shot[index].push_back({cnt, val});
    }
    
    int snap() {
        cnt++;
        return cnt-1;
    }
    
    int get(int index, int snap_id) {
        int l=0, r = shot[index].size()-1;
        while(l<=r){
            int mid = l+(r-l)/2;
            if(shot[index][mid].first==snap_id)
                return shot[index][mid].second;
            else if(shot[index][mid].first<snap_id){
                l=mid+1;
            }
            else r=mid-1;
        }
        return shot[index][r].second;
    }
};

/**
 * Your SnapshotArray object will be instantiated and called as such:
 * SnapshotArray* obj = new SnapshotArray(length);
 * obj->set(index,val);
 * int param_2 = obj->snap();
 * int param_3 = obj->get(index,snap_id);
 */

posted on 2022-09-05 16:56  Blackzxy  阅读(15)  评论(0编辑  收藏  举报