1357.每隔 n 个顾客打折:哈希表(设计)

【LetMeFly】1357.每隔 n 个顾客打折:哈希表(设计)

力扣题目链接:https://leetcode.cn/problems/apply-discount-every-n-orders/

超市里正在举行打折活动,每隔 n 个顾客会得到 discount 的折扣。

超市里有一些商品,第 i 种商品为 products[i] 且每件单品的价格为 prices[i] 。

结账系统会统计顾客的数目,每隔 n 个顾客结账时,该顾客的账单都会打折,折扣为 discount (也就是如果原本账单为 x ,那么实际金额会变成 x - (discount * x) / 100 ),然后系统会重新开始计数。

顾客会购买一些商品, product[i] 是顾客购买的第 i 种商品, amount[i] 是对应的购买该种商品的数目。

请你实现 Cashier 类:

  • Cashier(int n, int discount, int[] products, int[] prices) 初始化实例对象,参数分别为打折频率 n ,折扣大小 discount ,超市里的商品列表 products 和它们的价格 prices 。
  • double getBill(int[] product, int[] amount) 返回账单的实际金额(如果有打折,请返回打折后的结果)。返回结果与标准答案误差在 10^-5 以内都视为正确结果。

 

示例 1:

输入
["Cashier","getBill","getBill","getBill","getBill","getBill","getBill","getBill"]
[[3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]],[[1,2],[1,2]],[[3,7],[10,10]],[[1,2,3,4,5,6,7],[1,1,1,1,1,1,1]],[[4],[10]],[[7,3],[10,10]],[[7,5,3,1,6,4,2],[10,10,10,9,9,9,7]],[[2,3,5],[5,3,2]]]
输出
[null,500.0,4000.0,800.0,4000.0,4000.0,7350.0,2500.0]
解释
Cashier cashier = new Cashier(3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]);
cashier.getBill([1,2],[1,2]);                        // 返回 500.0, 账单金额为 = 1 * 100 + 2 * 200 = 500.
cashier.getBill([3,7],[10,10]);                      // 返回 4000.0
cashier.getBill([1,2,3,4,5,6,7],[1,1,1,1,1,1,1]);    // 返回 800.0 ,账单原本为 1600.0 ,但由于该顾客是第三位顾客,他将得到 50% 的折扣,所以实际金额为 1600 - 1600 * (50 / 100) = 800 。
cashier.getBill([4],[10]);                           // 返回 4000.0
cashier.getBill([7,3],[10,10]);                      // 返回 4000.0
cashier.getBill([7,5,3,1,6,4,2],[10,10,10,9,9,9,7]); // 返回 7350.0 ,账单原本为 14700.0 ,但由于系统计数再次达到三,该顾客将得到 50% 的折扣,实际金额为 7350.0 。
cashier.getBill([2,3,5],[5,3,2]);                    // 返回 2500.0

 

提示:

  • 1 <= n <= 10^4
  • 0 <= discount <= 100
  • 1 <= products.length <= 200
  • 1 <= products[i] <= 200
  • products 列表中 不会 有重复的元素。
  • prices.length == products.length
  • 1 <= prices[i] <= 1000
  • 1 <= product.length <= products.length
  • product[i] 在 products 出现过。
  • amount.length == product.length
  • 1 <= amount[i] <= 1000
  • 最多有 1000 次对 getBill 函数的调用。
  • 返回结果与标准答案误差在 10^-5 以内都视为正确结果。

解题方法:哈希表

为了方便后续快速查询某个product的价格,可以在初始化Cashier类时使用一个哈希表存下商品到价格的映射。

使用一个变量记录这是第几次bill,如果是$n$的倍数次则打折。

当然也可以提前算出打折的话是乘以百分之多少,避免后续每次重复计算$x - \frac{(discount \times x)}{100}$。

  • 时间复杂度:初始化期望为$O(P)$,每次调用getBill期望$O(K)$,其中$P$为商品种类数,$K$为本次账单中的商品种类数。
  • 空间复杂度:$O(P)$。

AC代码

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*
* @LastEditTime: 2026-11-30 12:55:38
*/
class Cashier {
private:
int n, th;
double percentage;
unordered_map<int, int> product2price;
public:
Cashier(int n, int discount, vector<int>& products, vector<int>& prices) {
this->n = n;
this->percentage = 1. * (100 - discount) / 100;
for (size_t i = 0, n = products.size(); i < n; i++) {
product2price[products[i]] = prices[i];
}
th = 0;
}

double getBill(vector<int> product, vector<int> amount) {
int original = 0;
for (size_t i = 0, n = product.size(); i < n; i++) {
original += product2price[product[i]] * amount[i];
}

if (++th % n == 0) {
return percentage * original;
}
return original;
}
};

/**
* Your Cashier object will be instantiated and called as such:
* Cashier* obj = new Cashier(n, discount, products, prices);
* double param_1 = obj->getBill(product,amount);
*/

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
'''
LastEditTime: 2026-11-30 13:59:33
'''
class Cashier:

def __init__(self, n: int, discount: int, products: list[int], prices: list[int]):
self.n = n
self.th = 0
self.percentage = 1 - discount / 100
self.p2p = dict()
for i, p in enumerate(products):
self.p2p[p] = prices[i]

def getBill(self, product: list[int], amount: list[int]) -> float:
price = 0
for i, p in enumerate(product):
price += self.p2p[p] * amount[i]
self.th += 1
return self.percentage * price if self.th % self.n == 0 else price


# Your Cashier object will be instantiated and called as such:
# obj = Cashier(n, discount, products, prices)
# param_1 = obj.getBill(product,amount)

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*
* @LastEditTime: 2026-11-30 13:09:52
*/
import java.util.Map;
import java.util.HashMap;

class Cashier {
private int n, th = 0;
private double percentage;
private Map<Integer, Integer> p2p;

public Cashier(int n, int discount, int[] products, int[] prices) {
this.n = n;
percentage = 1 - (double)discount / 100;
p2p = new HashMap<>();
for (int i = 0; i < products.length; i++) {
p2p.put(products[i], prices[i]);
}
}

public double getBill(int[] product, int[] amount) {
int price = 0;
for (int i = 0, n = product.length; i < n; i++) {
price += p2p.get(product[i]) * amount[i];
}
return ++th % n == 0 ? percentage * price : price;
}
}

/**
* Your Cashier object will be instantiated and called as such:
* Cashier obj = new Cashier(n, discount, products, prices);
* double param_1 = obj.getBill(product,amount);
*/

Go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*
* @LastEditTime: 2026-11-30 13:02:24
*/
package main

type Cashier struct {
products2prices map[int]int
n, th int
percentag float64
}


func Constructor(n int, discount int, products []int, prices []int) Cashier {
products2prices := make(map[int]int)
for i, p := range products {
products2prices[p] = prices[i]
}
return Cashier{
products2prices,
n,
0,
float64(100 - discount) / 100,
}
}


func (this *Cashier) GetBill(product []int, amount []int) float64 {
price := 0
for i, p := range product {
price += this.products2prices[p] * amount[i]
}
this.th++
if this.th % this.n == 0 {
return this.percentag * float64(price)
}
return float64(price)
}


/**
* Your Cashier object will be instantiated and called as such:
* obj := Constructor(n, discount, products, prices);
* param_1 := obj.GetBill(product,amount);
*/

Rust

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
* @LastEditTime: 2026-11-30 18:18:29
*/
use std::collections::HashMap;

struct Cashier {
n: i32,
th: i32,
percentage: f64,
p2p: HashMap<i32, i32>,
}


/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl Cashier {

fn new(n: i32, discount: i32, products: Vec<i32>, prices: Vec<i32>) -> Self {
let mut p2p = HashMap::new();
for (product, price) in products.into_iter().zip(prices.into_iter()) {
p2p.insert(product, price);
}

Self {
n,
th: 0,
percentage: 1.0 - discount as f64 / 100.,
p2p
}
}

fn get_bill(&mut self, product: Vec<i32>, amount: Vec<i32>) -> f64 {
let price = product.iter()
.zip(amount.iter())
.map(|(p, a)| self.p2p[p] * *a)
.sum::<i32>() as f64;
self.th += 1;
if self.th % self.n == 0 {
self.percentage * price
} else {
price
}
}
}

/**
* Your Cashier object will be instantiated and called as such:
* let obj = Cashier::new(n, discount, products, prices);
* let ret_1: f64 = obj.get_bill(product, amount);
*/

End

同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~

千篇源码题解已开源


1357.每隔 n 个顾客打折:哈希表(设计)
https://blog.letmefly.xyz/2026/11/30/LeetCode 1357.每隔n个顾客打折/
作者
发布于
2026年11月30日
许可协议