herrDeng網內搜尋

自訂搜尋

Ads

2025年2月14日 星期五

C++ OOP Prefix Product解Leetcode 1352 Product of the Last K Numbers


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)
[C++解請進]
-----
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)

  1. class ProductOfNumbers {
  2. public:
  3. vector product={1};
  4. int n=1;
  5. ProductOfNumbers(){
  6. product.reserve(40000);
  7. }
  8. void add(int num) {
  9. if (num==0) {
  10. product={1};
  11. n=1;
  12. }
  13. else{
  14. product.push_back(product[n++-1]*num);
  15. }
  16. }
  17. int getProduct(int k) {
  18. if (n<=k) return 0;
  19. return product[n-1]/product[n-k-1];
  20. }
  21. };
  22. /**
  23. * Your ProductOfNumbers object will be instantiated and called as such:
  24. * ProductOfNumbers* obj = new ProductOfNumbers();
  25. * obj->add(num);
  26. * int param_2 = obj->getProduct(k);
  27. */

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章