一、Problem
There is a room with n bulbs, numbered from 1 to n, arranged in a row from left to right. Initially, all the bulbs are turned off.
At moment k (for k from 0 to n - 1), we turn on the light[k] bulb. A bulb change color to blue only if it is on and all the previous bulbs (to the left) are turned on too.
Return the number of moments in which all turned on bulbs are blue.
二、Solution
方法一:記錄最大值
- 因爲所有燈最後都會被點亮,我們要求的是部分或全部等一排連續藍色的時刻數。
- 所以,我們可記錄每一個被打開的燈的最大位置 max,如果當前時刻 ,達到這個 max,證明這個時刻是存在連續一排藍色燈的。
- 也就是說當我們打開的燈的位置 max 遠遠大於當前時刻 ,就不會存在連續的一排藍色燈。
class Solution {
public int numTimesAllBlue(int[] lig) {
int mom = 0, max = 0;
for (int i = 0; i < lig.length; i++) {
if (lig[i] > max) max = lig[i]
if (i + 1 == max) mom++;
}
return mom;
}
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,