LeetCode 2960.统计已测试设备

文章讲述了在一个表示设备电池百分比的整数数组中,按照顺序执行测试操作,每个设备若电量大于0则增加已测试设备数并调整后续设备电量。提供了两种解决方案,一种是遍历并计算未测试设备,另一种是直接记录已测试设备。两种方法的时间复杂度均为O(n),空间复杂度为O(1)。
摘要由CSDN通过智能技术生成

给你一个长度为 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

法一:遍历输入数组,记下未测试数量即可:

class Solution {
public:
    int countTestedDevices(vector<int>& batteryPercentages) {
        int notTestNum = 0;
        for (int i = 0; i < batteryPercentages.size(); ++i)
        {
            // 如果当前遍历到的设备之前的设备都测试过,则应该减i,但还有notTestNum个未测试设备
            if (batteryPercentages[i] - i + notTestNum <= 0)
            {
                ++notTestNum;
            }
        }

        return batteryPercentages.size() - notTestNum;
    }
};

如果batteryPercentages的长度为n,则此算法时间复杂度为O(n),空间复杂度为O(1)。

法二:刚意识到直接记录已测试的数量代替未测试的数量,直接就是答案:

class Solution {
public:
    int countTestedDevices(vector<int>& batteryPercentages) {
        int testNum = 0;
        for (int i = 0; i < batteryPercentages.size(); ++i)
        {
            if (batteryPercentages[i] - testNum > 0)
            {
                ++testNum;
            }
        }

        return testNum;
    }
};

如果batteryPercentages的长度为n,则此算法时间复杂度为O(n),空间复杂度为O(1)。

  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值