[Binary search] leetcode 1146 Snapshot Array

problem:https://leetcode.com/problems/snapshot-array/

        This question of violence do (all the snapshots are kept down) would exceed the space constraints, it is necessary to reduce the use of space, twice a direct snapshot does not change the value there is no need duplicate records. When using a binary search, the value of each modification when the record about the current value of the snapshot, and then find the value of each index specific snapshot id current look less than equal to the value corresponding to the snapshot id.

class SnapshotArray {
public:
    unordered_map<int, map<int, int>> arr;
    SnapshotArray(int length) {
        
    }
    
    void set(int index, int val) {
        arr[index][count] = val;
    }
    
    int count = 0;
    int snap() {
        return count++;
    }
    
    int get(int index, int snap_id) {
        if(arr.find(index) == arr.end()) return 0;
       
        auto it = arr[index].upper_bound(snap_id);
        if(it == arr[index].begin())
        {
            return 0;
        }

        return prev(it)->second;
    }
};

 

Guess you like

Origin www.cnblogs.com/fish1996/p/11298130.html