C++ OOP Prefix Product解Leetcode 1352 Product of the Last K Numbers
Leetcode這題1352. Product of the Last K Numbers,是很好的OOP題目,除了談談class之外,還能練習一下prefix product的概念(與prefix sum類似但要小心0)
-----
Leetcode question 1352. Product of the Last K Numbers is a good OOP question. In addition to talking about class, you can also practice the concept of prefix product (similar to prefix sum but be careful with 0)
[codes on Leetcode]https://leetcode.com/problems/product-of-the-last-k-numbers/solutions/6419768/prefix-product-12ms-beats-91-95/
[Prefix Sum playlist]https://www.youtube.com/watch?v=1kA_aZHewmU&list=PLYRlUBnWnd5LkYN-5ptHDrtPXOuHm9uSq
class ProductOfNumbers {
public:
vector product={1};
int n=1;
ProductOfNumbers(){
product.reserve(40000);
}
void add(int num) {
if (num==0) {
product={1};
n=1;
}
else{
product.push_back(product[n++-1]*num);
}
}
int getProduct(int k) {
if (n<=k) return 0;
return product[n-1]/product[n-k-1];
}
};
/**
* Your ProductOfNumbers object will be instantiated and called as such:
* ProductOfNumbers* obj = new ProductOfNumbers();
* obj->add(num);
* int param_2 = obj->getProduct(k);
*/
沒有留言:
張貼留言