LeetCode 1352. Product of the Last K Numbers

47 阅读1分钟

🔗 leetcode.com/problems/pr…

题目

  • 实现一个类,可以添加元素,也可以返回最近添加 k 个元素的乘积

思路

  • 用 vector 存储元素
  • 朴素的代码,把最近的 k 个元素相乘可以通过
  • 优化的思路,是记录 pre-product,需要处理的是特殊情况,有 0 的元素,reset 清零

代码

class ProductOfNumbers {
public:
    ProductOfNumbers() {
    }
    
    void add(int num) {
        vec.push_back(num);
    }
    
    int getProduct(int k) {
        int product = 1;
        for (int i = vec.size() - k; i < vec.size(); i++) {
            product *= vec[i];
        }
        return product;
        
    }

    vector<int> vec;
};

/**
 * Your ProductOfNumbers object will be instantiated and called as such:
 * ProductOfNumbers* obj = new ProductOfNumbers();
 * obj->add(num);
 * int param_2 = obj->getProduct(k);
 */