LC每日一题|20240510 - 2960. 统计已测试设备

59 阅读2分钟

LC每日一题|20240510 - 2960. 统计已测试设备

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

你的任务是按照顺序测试每个设备 i,执行以下测试操作:

  • 如果 batteryPercentages[i] 大于 0

    • 增加 已测试设备的计数。
    • 将下标在 [i + 1, n - 1] 的所有设备的电池百分比减少 1,确保它们的电池百分比 不会低于 0 ,即 batteryPercentages[j] = max(0, batteryPercentages[j] - 1)
    • 移动到下一个设备。
  • 否则,移动到下一个设备而不执行任何测试。

返回一个整数,表示按顺序执行测试操作后 已测试设备 的数量。

提示:

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

题目等级:Easy

解题思路

如果只以AC为目标的话,直接逐字翻译就可以啦~

但仔细读读题可以发现,这题还有一种O(n)的方案~

每个设备电量的减少只发生在之前的某个设备满足测试条件的前提下,而该设备最终会减少的电量就等于移动到该设备的时候已测试设备的数量。

AC代码

class Solution {
    // 给你一个长度为 `n` 、下标从 **0** 开始的整数数组 `batteryPercentages` ,表示 `n` 个设备的电池百分比。
    fun countTestedDevices(batteryPercentages: IntArray): Int {
        var res = 0
        // 你的任务是按照顺序测试每个设备 `i`,执行以下测试操作:
        for (i in batteryPercentages.indices) {
            // 如果 `batteryPercentages[i]` **大于** `0`:
            if (batteryPercentages[i] > 0) {
                // **增加** 已测试设备的计数。
                res++
                // 将下标在 `[i + 1, n - 1]` 的所有设备的电池百分比减少 `1`,确保它们的电池百分比 **不会低于** `0` ,即 `batteryPercentages[j] = max(0, batteryPercentages[j] - 1)`。
                for (j in i + 1 until batteryPercentages.size) {
                    batteryPercentages[j] = Math.max(0, batteryPercentages[j] - 1)
                }
            }
        }
        // 返回一个整数,表示按顺序执行测试操作后 **已测试设备** 的数量。
        return res
    }
}

时间复杂度:O(n^2)

空间复杂度:O(1)

经过优化之后

class Solution {
    fun countTestedDevices(batteryPercentages: IntArray): Int {
        var res = 0
        batteryPercentages.forEach { if (it > res) res++ }
        return res
    }
}

时间复杂度:O(n)

空间复杂度:O(1)