1 class ProductOfNumbers:
 2     def __init__(self):
 3         self.matrix = []
 4         self.preproducts = []
 5         self.length = 0
 6         self.zeros = set()
 7 
 8     def add(self, num: int) -> None:
 9         self.matrix.append(num)
10         if num == 0:
11             self.zeros.add(self.length)
12         if self.length == 0:
13             self.preproducts.append(num)
14         else:
15             pre = self.preproducts[-1]
16             if pre == 0:
17                 self.preproducts.append(num)
18             else:
19                 self.preproducts.append(num * pre)
20         self.length += 1
21 
22     def getProduct(self, k: int) -> int:
23         j = self.length - 1
24         i = self.length - k - 1
25         if j - i  == 1:
26             return self.matrix[j]
27         for x in self.zeros:
28             if x > i and x <= j:
29                 return 0
30         if i < 0:
31             return self.preproducts[j]
32         return self.preproducts[j] // self.preproducts[i] if self.preproducts[i] != 0 else self.preproducts[j]

 

posted on 2020-02-16 14:34  Sempron2800+  阅读(152)  评论(0编辑  收藏  举报