每隔 n 个顾客打折
难度:
标签:
题目描述
代码结果
运行时间: 92 ms, 内存: 28.6 MB
/* 思路:
1. 使用 Java Stream API 优化代码。
2. 使用 IntStream 和 mapToDouble 方法简化账单计算。
*/
import java.util.HashMap;
import java.util.Map;
import java.util.stream.IntStream;
public class Cashier {
private int n;
private int discount;
private int customerCount;
private Map<Integer, Integer> productPriceMap;
public Cashier(int n, int discount, int[] products, int[] prices) {
this.n = n;
this.discount = discount;
this.customerCount = 0;
productPriceMap = new HashMap<>();
for (int i = 0; i < products.length; i++) {
productPriceMap.put(products[i], prices[i]);
}
}
public double getBill(int[] product, int[] amount) {
customerCount++;
double total = IntStream.range(0, product.length)
.mapToDouble(i -> productPriceMap.get(product[i]) * amount[i])
.sum();
if (customerCount % n == 0) {
total -= (discount * total / 100.0);
}
return total;
}
}
解释
方法:
这个题解的思路是首先在构造函数中创建一个字典 price_map 将产品 ID 和其价格对应起来,以便快速查找每个产品的价格。然后,在 getBill 函数中,遍历顾客购买的每种产品和数量,计算总账单金额。如果顾客是每 n 个顾客之一,则给予折扣。折扣是通过将总账单金额减去其与折扣比例的乘积来计算的。最后,如果给予了折扣,则重置顾客计数器;否则,增加顾客计数器。
时间复杂度:
O(m)
空间复杂度:
O(p)
代码细节讲解
🦆
构造函数中使用了字典来映射产品ID和价格,这种数据结构选择的依据是什么?为什么不使用其他类型的数据结构?
▷🦆
如何处理在product数组中存在但在products初始化列表中不存在的商品ID?即getBill方法中如果某个商品ID不存在于price_map中应如何处理?
▷🦆
getBill方法中,顾客计数器的更新是在计算折扣之后进行的,这种设计有什么特定的原因吗?
▷🦆
在计算折扣时使用了`(self.discount * total_bill) / 100`的表达式,这种计算方式是否会因为浮点数的精度问题而导致计算误差?如果会,有什么可能的解决办法?
▷