LeetCode #1352 Product of the Last K Numbers 最后 K 個數(shù)的乘積

1352 Product of the Last K Numbers 最后 K 個數(shù)的乘積

Description:

Design an algorithm that accepts a stream of integers and retrieves the product of the last k integers of the stream.

Implement the ProductOfNumbers class:

ProductOfNumbers() Initializes the object with an empty stream.
void add(int num) Appends the integer num to the stream.
int getProduct(int k) Returns the product of the last k numbers in the current list. You can assume that always the current list has at least k numbers.
The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing.

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:

0 <= num <= 100
1 <= k <= 4 * 10^4
At most 4 * 104 calls will be made to add and getProduct.
The product of the stream at any point in time will fit in a 32-bit integer.

題目描述:

請你實現(xiàn)一個「數(shù)字乘積類」ProductOfNumbers,要求支持下述兩種方法:

  1. add(int num)

將數(shù)字 num 添加到當(dāng)前數(shù)字列表的最后面。

  1. getProduct(int k)

返回當(dāng)前數(shù)字列表中,最后 k 個數(shù)字的乘積。
你可以假設(shè)當(dāng)前列表中始終 至少 包含 k 個數(shù)字。
題目數(shù)據(jù)保證:任何時候,任一連續(xù)數(shù)字序列的乘積都在 32-bit 整數(shù)范圍內(nèi),不會溢出。

示例:

輸入:
["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"]
[[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]

輸出:
[null,null,null,null,null,null,20,40,0,null,32]

解釋:

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); // 返回 20 。最后 2 個數(shù)字的乘積是 5 * 4 = 20
productOfNumbers.getProduct(3); // 返回 40 。最后 3 個數(shù)字的乘積是 2 * 5 * 4 = 40
productOfNumbers.getProduct(4); // 返回  0 。最后 4 個數(shù)字的乘積是 0 * 2 * 5 * 4 = 0
productOfNumbers.add(8);        // [3,0,2,5,4,8]
productOfNumbers.getProduct(2); // 返回 32 。最后 2 個數(shù)字的乘積是 4 * 8 = 32 

提示:

add 和 getProduct 兩種操作加起來總共不會超過 40000 次。
0 <= num <= 100
1 <= k <= 40000

思路:

前綴積
如果 add 的數(shù)為 0, 清空數(shù)組
如果數(shù)組為空, 先加入哨兵 1
然后加入數(shù)組最后一個數(shù)和當(dāng)前數(shù)的乘積
返回最后一個數(shù)和倒數(shù)第 k 個數(shù)的商
add 函數(shù)時間復(fù)雜度為 O(n), getProduct 函數(shù)時間復(fù)雜度為 O(1), 空間復(fù)雜度為 O(n)

代碼:

C++:

class ProductOfNumbers 
{
private:
    vector<int> pre;
public:
    ProductOfNumbers() {}
    
    void add(int num) 
    {
        if (!num) 
        {
            pre.clear();
            return;
        }
        if (pre.empty()) pre.emplace_back(1);
        pre.emplace_back(pre.back() * num); 
    }
    
    int getProduct(int k) 
    {
        return k < pre.size() ? pre.back() / pre[pre.size() - 1 - k] : 0;
    }
};

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

Java:

class ProductOfNumbers {
    private List<Integer> pre;

    public ProductOfNumbers() {
        pre = new ArrayList<>();
    }
    
    public void add(int num) {
        if (num == 0) {
            pre.clear();
            return;
        }
        if (pre.isEmpty()) pre.add(1);
        pre.add(pre.get(pre.size() - 1) * num); 
    }
    
    public int getProduct(int k) {
        return k < pre.size() ? pre.get(pre.size() - 1) / pre.get(pre.size() - 1 - k) : 0;
    }
}

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

Python:

class ProductOfNumbers:

    def __init__(self):
        self.pre = []


    def add(self, num: int) -> None:
        if not num:
            self.pre = []
            return
        if not self.pre:
            self.pre.append(1)
        self.pre.append(self.pre[-1] * num)


    def getProduct(self, k: int) -> int:
        return 0 if k >= len(self.pre) else self.pre[-1] // self.pre[-1 - k]



# Your ProductOfNumbers object will be instantiated and called as such:
# obj = ProductOfNumbers()
# obj.add(num)
# param_2 = obj.getProduct(k)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容