Re: [閒聊] 每日leetcode

看板Marginalman作者 (dont)時間9月前 (2025/02/14 20:11), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串1334/1552 (看更多)
1352. Product of the Last K Numbers ## 思路 Prefix Product 用size_紀錄目前Product的個數 如果add 0 就reset Prefix跟size_ getProduct: prefix[-1] / prefix[size_-k] ## CODE ```cpp class ProductOfNumbers { public: ProductOfNumbers() { product_ = {1}; size_ = 0; } void add(int num) { if (num == 0) { product_.clear(); product_.push_back(1); size_ = 0; } else { product_.push_back(num * product_.back()); ++size_; } } int getProduct(int k) { if (k > size_) return 0; return product_.back() / product_[size_-k]; } private: vector<long long> product_; int size_; }; /** * Your ProductOfNumbers object will be instantiated and called as such: * ProductOfNumbers* obj = new ProductOfNumbers(); * obj->add(num); * int param_2 = obj->getProduct(k); */ ``` -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 138.199.21.53 (日本) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1739535090.A.573.html
文章代碼(AID): #1dhpBoLp (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1dhpBoLp (Marginalman)