问题:
求两个接口,使得,
add接口,向列表中添加元素,
getProduct(k)接口,可得最后添加的k个元素的乘积。
Example: Input ["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"] [[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]] Output [null,null,null,null,null,null,20,40,0,null,32] Explanation ProductOfNumbers productOfNumbers = new ProductOfNumbers(); productOfNumbers.add(3); // [3] productOfNumbers.add(0); // [3,0] productOfNumbers.add(2); // [3,0,2] productOfNumbers.add(5); // [3,0,2,5] productOfNumbers.add(4); // [3,0,2,5,4] productOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 * 4 = 20 productOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 * 5 * 4 = 40 productOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 * 2 * 5 * 4 = 0 productOfNumbers.add(8); // [3,0,2,5,4,8] productOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 * 8 = 32 Constraints: There will be at most 40000 operations considering both add and getProduct. 0 <= num <= 100 1 <= k <= 40000
解法:
前缀和法
各个添加元素位置上为,累计到目前为止所有元素的乘积PreSum(cur)
要求则为,
getProduct(k)=
PreSum(last) / Presum(last-k-1)
♻️ 优化:按照乘法规则X0的话,前面的所有结果都=0
getProduct(k)=
PreSum(last) / Presum(last-k-1) = 0/x = 0
因此,若插入新的0元素,则可清空前面的累计Presum
代码参考:
1 class ProductOfNumbers { 2 public: 3 vector<int> pro; 4 ProductOfNumbers() { 5 pro={1}; 6 } 7 8 void add(int num) { 9 if(num==0){ 10 pro={1}; 11 }else{ 12 pro.push_back(num*pro.back()); 13 } 14 } 15 16 int getProduct(int k) { 17 return k<pro.size()?pro.back()/pro[pro.size()-k-1]:0; 18 } 19 }; 20 21 /** 22 * Your ProductOfNumbers object will be instantiated and called as such: 23 * ProductOfNumbers* obj = new ProductOfNumbers(); 24 * obj->add(num); 25 * int param_2 = obj->getProduct(k); 26 */