LeetCode 1375. Bulb Switcher III
Question
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.
Example
1 | Input: light = [2,1,3,5,4] |
Solution
比赛的时候没有做出来这个题,当时想的过于复杂。
- 方法一:主要利用一个maxTurnOn来记录目前为止连续亮的灯是多少个,与当前的index + 1比较(index + 1可以表示目前我们开启了几盏灯)。如果两者相同,则表示达到目标状态,结果加1。
- 方法二:或者更加简单的方式,用一个变量来维护最远能开的灯,如果当前的个数与这个最远的灯重合,结果加1。
Code
1 | // time:O(n) space:O(n) |