-
发表于 2024.08.30
-
很简单的哈希表应用题,使用一个哈希表记录商品id和价格的映射关系,然后每次调用
getBill
计算账单时,累加商品价格,如果当前是第n个顾客,那么就打折。C++的做法:
class Cashier { public: Cashier(int n, int discount, vector<int>& products, vector<int>& prices) : n(n), discount(discount) { for (int i = 0; i < products.size(); ++i) price_map.insert({ products[i], prices[i] }); } double getBill(vector<int> product, vector<int> amount) { double total = 0; for (int i = 0; i < product.size(); ++i) total += price_map[product[i]] * amount[i]; if (++processed % n == 0) total = total * ((100 - discount) / 100.0); return total; } private: int n; int discount; int processed {0}; unordered_map<int, int> price_map; };
Python的做法:
class Cashier: def __init__(self, n: int, discount: int, products: List[int], prices: List[int]): self._price_map = {product: price for product, price in zip(products, prices)} self._n = n self._discount = discount self._processed = 0 def getBill(self, product: List[int], amount: List[int]) -> float: self._processed += 1 total = sum(self._price_map[product_id] * cnt for product_id, cnt in zip(product, amount)) if not self._processed % self._n: total = total * ((100 - self._discount) / 100) return float(total)
- LC 题目链接
-