1146. 快照数组
题目:
思路:
【1】利用TreeMap解题
1)利用TreeMap来存储snap_id : val,然后再用一个Map来存储index : tree; 2)找index索引下的snap_id版本的值时,只需要找最大的小于等于snap_id版本的值,利用TreeMap.floorEntry(snap_id)来实现。
代码展示:
//时间69 ms 击败 21.27% //内存97.7 MB 击败 5.7% class SnapshotArray { // index : (snap_id : val) private Map<Integer, TreeMap<Integer, Integer>> map; private int snap_id; public SnapshotArray(int length) { map = new HashMap<>(); snap_id = 0; for (int i = 0; i < length; i++) { TreeMap<Integer, Integer> tree = new TreeMap<>(); tree.put(0, 0); map.put(i, tree); } } public void set(int index, int val) { TreeMap<Integer, Integer> tree = map.get(index); tree.put(snap_id, val); } public int snap() { return snap_id++; } public int get(int index, int snap_id) { TreeMap<Integer, Integer> tree = map.get(index); return tree.floorEntry(snap_id).getValue(); } } /** * 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); */ //简化的数据结果达成效果 //时间48 ms 击败 56.19% //内存81.2 MB 击败 29.83% class SnapshotArray { int id = 0; List<int[]>[] snapshots; public SnapshotArray(int length) { snapshots = new List[length]; for (int i = 0; i < length; i++) { snapshots[i] = new ArrayList<int[]>(); } } public void set(int index, int val) { snapshots[index].add(new int[]{id, val}); } public int snap() { return id++; } public int get(int index, int snap_id) { List<int[]> snaplist = snapshots[index]; int low = -1, high = snaplist.size() - 1; while (low < high) { int mid = low + (high - low + 1) / 2; if (snaplist.get(mid)[0] <= snap_id) { low = mid; } else { high = mid - 1; } } return low >= 0 ? snaplist.get(low)[1] : 0; } }