You are given a 0-indexed integer array batteryPercentages having length n, denoting the battery percentages of n 0-indexed devices.
Your task is to test each device i in order from 0 to n - 1, by performing the following test operations:
If batteryPercentages[i] is greater than 0:
Increment the count of tested devices.
Decrease the battery percentage of all devices with indices j in the range [i + 1, n - 1] by 1, ensuring their battery percentage never goes below 0, i.e, batteryPercentages[j] = max(0, batteryPercentages[j] - 1).
Move to the next device.
Otherwise, move to the next device without performing any test.
Return an integer denoting the number of devices that will be tested after performing the test operations in order.
Example 1:
Input: batteryPercentages = [1,1,2,1,3]
Output: 3
Explanation: Performing the test operations in order starting from device 0:
At device 0, batteryPercentages[0] > 0, so there is now 1 tested device, and batteryPercentages becomes [1,0,1,0,2].
At device 1, batteryPercentages[1] == 0, so we move to the next device without testing.
At device 2, batteryPercentages[2] > 0, so there are now 2 tested devices, and batteryPercentages becomes [1,0,1,0,1].
At device 3, batteryPercentages[3] == 0, so we move to the next device without testing.
At device 4, batteryPercentages[4] > 0, so there are now 3 tested devices, and batteryPercentages stays the same.
So, the answer is 3.
Example 2:
Input: batteryPercentages = [0,1,2]
Output: 2
Explanation: Performing the test operations in order starting from device 0:
At device 0, batteryPercentages[0] == 0, so we move to the next device without testing.
At device 1, batteryPercentages[1] > 0, so there is now 1 tested device, and batteryPercentages becomes [0,1,1].
At device 2, batteryPercentages[2] > 0, so there are now 2 tested devices, and batteryPercentages stays the same.
So, the answer is 2.
Constraints:
1 <= n == batteryPercentages.length <= 100
0 <= batteryPercentages[i] <= 100
統計已測試裝置。
給你一個長度為 n 、下標從 0 開始的整數陣列 batteryPercentages ,表示 n 個裝置的電池百分比。你的任務是按照順序測試每個裝置 i,執行以下測試操作:
如果 batteryPercentages[i] 大於 0:
增加 已測試裝置的計數。
將下標在 [i + 1, n - 1] 的所有裝置的電池百分比減少 1,確保它們的電池百分比 不會低於 0 ,即 batteryPercentages[j] = max(0, batteryPercentages[j] - 1)。
移動到下一個裝置。
否則,移動到下一個裝置而不執行任何測試。
返回一個整數,表示按順序執行測試操作後 已測試裝置 的數量。
思路
思路是差分陣列。暴力解就不展示了,思路是需要一個兩層 for 迴圈,第一層 for 是去遍歷每個裝置,如果當前裝置電量大於 0,則第二層 for 迴圈需要去遍歷剩下的裝置並對每個剩下的裝置的電池百分比 - 1。
這道題的最優解是差分陣列。還是需要遍歷一遍 input 陣列,遍歷的時候,如果當前裝置的電量大於 0,則 count++,count 記錄的是已測試過的裝置的數量。接著往之後的裝置看,如果當前裝置在按規則(電池百分比減少 1)減去電量之後,電量仍然大於 0,則 count++。最後返回的是 count。
複雜度
時間O(n)
空間O(1)
程式碼
Java實現
class Solution {
public int countTestedDevices(int[] batteryPercentages) {
int n = batteryPercentages.length;
int count = 0;
for (int i = 0; i < n; i++) {
batteryPercentages[i] = Math.max(0, batteryPercentages[i] - count);
if (batteryPercentages[i] > 0) {
count++;
}
}
return count;
}
}