标签:index snaps 1146 int self Snapshot snap Array id
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 givenindex
to be equal toval
.int snap()
takes a snapshot of the array and returns thesnap_id
: the total number of times we calledsnap()
minus1
.int get(index, snap_id)
returns the value at the givenindex
, at the time we took the snapshot with the givensnap_id
Solution0:
class SnapshotArray: def __init__(self, length: int): self.array = [[0] for i in range(length)] self.indx = [[0] for i in range(length)] self.snaps = 0 def set(self, index: int, val: int) -> None: snaps = self.snaps self.indx[index].append(snaps) self.array[index].append(val) def snap(self) -> int: self.snaps += 1 return self.snaps - 1 def get(self, index: int, snap_id: int) -> int: if not self.indx[index]: return 0 left = 0 right = len(self.indx[index]) - 1 while (left < right): mid = left + (right - left)//2 if (self.indx[index][mid] > snap_id): right = mid else: left = mid + 1 if self.indx[index][left] > snap_id: return self.array[index][left-1] else: return self.array[index][left]
Solution1:
class SnapshotArray(object): def __init__(self, length): """ :type length: int """ self.snaps = 0 self.store = dict() self.store[0] = dict() def set(self, index, val): """ :type index: int :type val: int :rtype: None """ self.store[self.snaps][index] = val def snap(self): """ :rtype: int """ self.snaps += 1 a = (self.store[self.snaps -1]).copy() self.store[self.snaps] = a return self.snaps -1 def get(self, index, snap_id): """ :type index: int :type snap_id: int :rtype: int """ if index in self.store[snap_id]: return self.store[snap_id][index] else: return 0
标签:index,snaps,1146,int,self,Snapshot,snap,Array,id 来源: https://www.cnblogs.com/beatets/p/12170846.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。