LeetCode 每日一题 ---- 【2960.统计已测试设备】
2960.统计已测试设备
方法:模拟+数组
简单的模拟题,遍历数组,暴力的话就是两次遍历第一次从 0 到 n - 1,判断 batteryPercentages[i] 是否大于 0,若大于 0,则遍历 i + 1 到 n - 1,并将值 - 1。可以优化的是,维护一个变量存储后续值需要减少的值,这样就只需要遍历一遍数组就可以了。
class Solution {
public int countTestedDevices(int[] batteryPercentages) {
int len = batteryPercentages.length;
int ans = 0;
int cur = 0;
for (int i = 0; i < len; i ++ ) {
if (batteryPercentages[i] - cur > 0) {
ans ++ ;
cur ++ ;
}
}
return ans;
}
}
时间复杂度:
O(n)
空间复杂度:
O(1)