[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

Example 1:

Input: ["SnapshotArray","set","snap","set","get"]
[[3],[0,5],[],[0,6],[0,0]]
Output: [null,null,0,null,5]
Explanation:
SnapshotArray snapshotArr = new SnapshotArray(3); // set the length to be 3
snapshotArr.set(0,5);  // Set array[0] = 5
snapshotArr.snap();  // Take a snapshot, return snap_id = 0
snapshotArr.set(0,6);
snapshotArr.get(0,0);  // Get the value of array[0] with snap_id = 0, return 5

Constraints:

  • 1 <= length <= 50000
  • At most 50000 calls will be made to setsnap, and get.
  • 0 <= index < length
  • 0 <= snap_id < (the total number of times we call snap())
  • 0 <= val <= 10^9

這道題讓實現一個 SnapshotArray 的類,具有給數組拍照的功能,就是說在某個時間點 spapId 拍照后,當前數組的值需要都記錄下來,同理,每一次調用 snap() 函數時,都需要記錄整個數組的狀態,這是為了之后可以查詢任意一個時間點上的任意一個位置上的值。最簡單粗暴的方法當前就是用一個二維數組,每次拍照的時候,都把整個數組都存到二維數組中,其坐標就是 snapId。但是這種方法不高效,而且占用了巨大的空間,被 OJ 豪不留情的抹殺掉了。來分析一下不高效的原因,這是因為每次拍照時,可能數組的大部分數據並沒有變動,每次都再存一遍整個數組是浪費的。這里我們關心的是調用 set() 函數,因為這會改變數組的值,若能建立 snapId 和更新值之間的映射,就可以根據二分法來快速定位某一個 snapId 的值了,因為 snapId 是按順序遞增的。這樣就可以用一個 Vector of Map 或者 Map of Map 的數據結構來實現,外層的 TreeMap 是映射建立數組坐標到內層 TreeMap 之間的映射,內層的 TreeMap 是建立 snapId 和更新值之間的映射。初始化時,要將 0->0 這個映射對兒加到每一個位置,因為初始化時數組的每個元素都是0。在 set() 函數中就可以更新 HashMap 中的映射值,snap() 就直接累加 snapId,比較麻煩的就是 get() 函數,給定的 snapId 可能在內層的 HashMap 中不存在,需要查找第一個不大於給定 snapId 的映射值,那么就先找第一個大於 snapId 的位置,再回退一位就好了,參見代碼如下:


class SnapshotArray {
public:
    SnapshotArray(int length) {
        for (int i = 0; i < length; ++i) {
            snapMap[i] = {{0, 0}};
        }
    }
    
    void set(int index, int val) {
        snapMap[index][snapId] = val;
    }
    
    int snap() {
        return snapId++;
    }
    
    int get(int index, int snap_id) {
        auto it = snapMap[index].upper_bound(snap_id);
        --it;
        return it->second;
    }

private:
    int snapId = 0;
    map<int, map<int, int>> snapMap;
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1146


參考資料:

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

https://leetcode.com/problems/snapshot-array/discuss/350562/JavaPython-Binary-Search


LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM