Easy

题目描述

给你一个长度为 n 的下标从 0 开始的整数数组 batteryPercentages,表示 n 个设备的电池百分比。

你的任务是按照从 0 到 n - 1 的顺序测试每个设备 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

提示:

  • 1 <= n == batteryPercentages.length <= 100
  • 0 <= batteryPercentages[i] <= 100

解题思路

这道题有两种解法思路:

方法一:模拟(朴素解法)

按照题目描述直接模拟整个过程。对于每个设备,如果电池百分比大于 0,就测试该设备并将后续所有设备的电池百分比减 1(不低于 0)。这种方法时间复杂度为 O(n²)。

方法二:优化解法(推荐)

关键观察:我们不需要真的去修改数组中的值。当我们测试一个设备时,它会让后续所有设备的电池百分比减 1。如果我们已经测试了 tested 个设备,那么当前设备的实际电池百分比就是 max(0, batteryPercentages[i] - tested)

因此,设备 i 能被测试的条件是:batteryPercentages[i] > tested,其中 tested 是之前已经测试的设备数量。

这种方法只需要一次遍历,时间复杂度为 O(n),空间复杂度为 O(1)。

代码实现

class Solution {
public:
    int countTestedDevices(vector<int>& batteryPercentages) {
        int tested = 0;
        for (int i = 0; i < batteryPercentages.size(); i++) {
            if (batteryPercentages[i] > tested) {
                tested++;
            }
        }
        return tested;
    }
};
class Solution:
    def countTestedDevices(self, batteryPercentages: List[int]) -> int:
        tested = 0
        for battery in batteryPercentages:
            if battery > tested:
                tested += 1
        return tested
public class Solution {
    public int CountTestedDevices(int[] batteryPercentages) {
        int tested = 0;
        for (int i = 0; i < batteryPercentages.Length; i++) {
            if (batteryPercentages[i] > tested) {
                tested++;
            }
        }
        return tested;
    }
}
/**
 * @param {number[]} batteryPercentages
 * @return {number}
 */
var countTestedDevices = function(batteryPercentages) {
    let tested = 0;
    for (let i = 0; i < batteryPercentages.length; i++) {
        if (batteryPercentages[i] > tested) {
            tested++;
        }
    }
    return tested;
};

复杂度分析

解法时间复杂度空间复杂度
优化解法O(n)O(1)
模拟解法O(n²)O(1)

其中 n 是数组 batteryPercentages 的长度。