Advertisement
smj007

Untitled

Mar 6th, 2024
756
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.93 KB | None | 0 0
  1. class SnapshotArray:
  2.  
  3.     def __init__(self, length: int):
  4.         self.history_record = defaultdict(list)
  5.         self.count = 0
  6.  
  7.     def set(self, index: int, val: int) -> None:
  8.         self.history_record[index].append([self.count, val])
  9.        
  10.     def snap(self) -> int:
  11.         self.count += 1
  12.         return self.count - 1
  13.  
  14.     def get(self, index: int, snap_id: int) -> int:
  15.         history = self.history_record[index]
  16.         low = 0; high = len(history) - 1
  17.         result = 0
  18.         while (low <= high):
  19.             mid = (low + high)//2
  20.  
  21.             if history[mid][0] <= snap_id:
  22.                 result = history[mid][1]
  23.                 low = mid + 1
  24.             else:
  25.                 high = mid - 1
  26.  
  27.         return result
  28.  
  29. # Your SnapshotArray object will be instantiated and called as such:
  30. # obj = SnapshotArray(length)
  31. # obj.set(index,val)
  32. # param_2 = obj.snap()
  33. # param_3 = obj.get(index,snap_id)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement