LeetCode 题解工作台
统计已测试设备
给你一个长度为 n 、下标从 0 开始的整数数组 batteryPercentages ,表示 n 个设备的电池百分比。 你的任务是按照顺序测试每个设备 i ,执行以下测试操作: 如果 batteryPercentages[i] 大于 0 : 增加 已测试设备的计数。 将下标 j 在 [i + 1,…
3
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·模拟
答案摘要
假设我们当前已测试的设备数量为 ,当测试新的一台设备 时,它的剩余电量为 $\max(0, batteryPercentages[i] - ans)$,如果剩余电量大于 ,则说明这台设备可以进行测试,此时我们需要将 增加 。 最后返回 即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·模拟 题型思路
题目描述
给你一个长度为 n 、下标从 0 开始的整数数组 batteryPercentages ,表示 n 个设备的电池百分比。
你的任务是按照顺序测试每个设备 i,执行以下测试操作:
- 如果
batteryPercentages[i]大于0:- 增加 已测试设备的计数。
- 将下标
j在[i + 1, n - 1]的所有设备的电池百分比减少1,确保它们的电池百分比 不会低于0,即batteryPercentages[j] = max(0, batteryPercentages[j] - 1)。 - 移动到下一个设备。
- 否则,移动到下一个设备而不执行任何测试。
返回一个整数,表示按顺序执行测试操作后 已测试设备 的数量。
示例 1:
输入:batteryPercentages = [1,1,2,1,3] 输出:3 解释:按顺序从设备 0 开始执行测试操作: 在设备 0 上,batteryPercentages[0] > 0 ,现在有 1 个已测试设备,batteryPercentages 变为 [1,0,1,0,2] 。 在设备 1 上,batteryPercentages[1] == 0 ,移动到下一个设备而不进行测试。 在设备 2 上,batteryPercentages[2] > 0 ,现在有 2 个已测试设备,batteryPercentages 变为 [1,0,1,0,1] 。 在设备 3 上,batteryPercentages[3] == 0 ,移动到下一个设备而不进行测试。 在设备 4 上,batteryPercentages[4] > 0 ,现在有 3 个已测试设备,batteryPercentages 保持不变。 因此,答案是 3 。
示例 2:
输入:batteryPercentages = [0,1,2] 输出:2 解释:按顺序从设备 0 开始执行测试操作: 在设备 0 上,batteryPercentages[0] == 0 ,移动到下一个设备而不进行测试。 在设备 1 上,batteryPercentages[1] > 0 ,现在有 1 个已测试设备,batteryPercentages 变为 [0,1,1] 。 在设备 2 上,batteryPercentages[2] > 0 ,现在有 2 个已测试设备,batteryPercentages 保持不变。 因此,答案是 2 。
提示:
1 <= n == batteryPercentages.length <= 1000 <= batteryPercentages[i] <= 100
解题思路
方法一:模拟
假设我们当前已测试的设备数量为 ,当测试新的一台设备 时,它的剩余电量为 ,如果剩余电量大于 ,则说明这台设备可以进行测试,此时我们需要将 增加 。
最后返回 即可。
时间复杂度 ,其中 为数组长度。空间复杂度 。
class Solution:
def countTestedDevices(self, batteryPercentages: List[int]) -> int:
ans = 0
for x in batteryPercentages:
ans += x > ans
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for the candidate's ability to implement sequential testing and handle array manipulations.
- question_mark
Evaluate their understanding of simulation techniques in algorithm design.
- question_mark
Check how they approach optimizing the simulation for better time complexity.
常见陷阱
外企场景- error
Overcomplicating the solution by attempting unnecessary optimizations for this simple problem.
- error
Not handling the case where a device has zero battery properly, skipping it in the correct order.
- error
Assuming there's an obvious faster solution without considering the inherent simulation nature of the task.
进阶变体
外企场景- arrow_right_alt
Change the condition for when a device is considered tested (e.g., after a certain battery threshold is reached).
- arrow_right_alt
Add more operations after testing, such as recharging devices or resetting battery percentages.
- arrow_right_alt
Simulate testing with additional variables or constraints, such as multiple battery-charging cycles.