🚀 算法题 🚀 |
🌲 算法刷题专栏 | 面试必备算法 | 面试高频算法 🍀
🌲 越难的东西,越要努力坚持,因为它具有很高的价值,算法就是这样✨
🌲 作者简介:硕风和炜,CSDN-Java领域优质创作者🏆,保研|国家奖学金|高中学习JAVA|大学完善JAVA开发技术栈|面试刷题|面经八股文|经验分享|好用的网站工具分享💎💎💎
🌲 恭喜你发现一枚宝藏博主,赶快收入囊中吧🌻
🌲 人生如棋,我愿为卒,行动虽慢,可谁曾见我后退一步?🎯🎯
🚀 算法题 🚀 |
🚩 题目链接
⛲ 题目描述
给你一个长度为 n 、下标从 0 开始的整数数组 batteryPercentages ,表示 n 个设备的电池百分比。
你的任务是按照顺序测试每个设备 i,执行以下测试操作:
如果 batteryPercentages[i] 大于 0:
增加 已测试设备的计数。
将下标在 [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 <= 100
0 <= batteryPercentages[i] <= 100
🌟 求解思路&实现代码&运行结果
⚡ 模拟
🥦 求解思路
- 该题目思路比较简单,直接根据给定的规则直接模拟即可。
- 有了基本的思路,接下来我们就来通过代码来实现一下。
🥦 实现代码
版本1
class Solution {
public int countTestedDevices(int[] batteryPercentages) {
if (batteryPercentages == null || batteryPercentages.length <= 0)
return 0;
int n = batteryPercentages.length, cnt = 0;
for (int i = 0; i < n; i++) {
if (batteryPercentages[i] > 0) {
cnt++;
int j = i + 1;
while (j < n) {
batteryPercentages[j] = Math.max(batteryPercentages[j] - 1, 0);
j++;
}
}
}
return cnt;
}
}
版本2
class Solution {
public int countTestedDevices(int[] batteryPercentages) {
int ans = 0;
for (int x : batteryPercentages) {
ans += x > ans ? 1 : 0;
}
return ans;
}
}
🥦 运行结果
💬 共勉
最后,我想和大家分享一句一直激励我的座右铭,希望可以与大家共勉! |