|
| 1 | +// Source : https://leetcode.com/problems/bulb-switcher-iii |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2021-03-29 |
| 4 | + |
| 5 | +/***************************************************************************************************** |
| 6 | + * |
| 7 | + * There is a room with n bulbs, numbered from 1 to n, arranged in a row from left to right. |
| 8 | + * Initially, all the bulbs are turned off. |
| 9 | + * |
| 10 | + * At moment k (for k from 0 to n - 1), we turn on the light[k] bulb. A bulb change color to blue only |
| 11 | + * if it is on and all the previous bulbs (to the left) are turned on too. |
| 12 | + * |
| 13 | + * Return the number of moments in which all turned on bulbs are blue. |
| 14 | + * |
| 15 | + * Example 1: |
| 16 | + * |
| 17 | + * Input: light = [2,1,3,5,4] |
| 18 | + * Output: 3 |
| 19 | + * Explanation: All bulbs turned on, are blue at the moment 1, 2 and 4. |
| 20 | + * |
| 21 | + * Example 2: |
| 22 | + * |
| 23 | + * Input: light = [3,2,4,1,5] |
| 24 | + * Output: 2 |
| 25 | + * Explanation: All bulbs turned on, are blue at the moment 3, and 4 (index-0). |
| 26 | + * |
| 27 | + * Example 3: |
| 28 | + * |
| 29 | + * Input: light = [4,1,2,3] |
| 30 | + * Output: 1 |
| 31 | + * Explanation: All bulbs turned on, are blue at the moment 3 (index-0). |
| 32 | + * Bulb 4th changes to blue at the moment 3. |
| 33 | + * |
| 34 | + * Example 4: |
| 35 | + * |
| 36 | + * Input: light = [2,1,4,3,6,5] |
| 37 | + * Output: 3 |
| 38 | + * |
| 39 | + * Example 5: |
| 40 | + * |
| 41 | + * Input: light = [1,2,3,4,5,6] |
| 42 | + * Output: 6 |
| 43 | + * |
| 44 | + * Constraints: |
| 45 | + * |
| 46 | + * n == light.length |
| 47 | + * 1 <= n <= 5 * 10^4 |
| 48 | + * light is a permutation of [1, 2, ..., n] |
| 49 | + ******************************************************************************************************/ |
| 50 | + |
| 51 | +class Solution { |
| 52 | +public: |
| 53 | + int numTimesAllBlue(vector<int>& light) { |
| 54 | + int n = light.size(); |
| 55 | + vector<bool> on(n, false); |
| 56 | + int left = 0; //tracking the most left place that all bubls are truned on. |
| 57 | + int result = 0; |
| 58 | + for(int i=0; i<light.size(); i++){ |
| 59 | + on[light[i]-1] = true; |
| 60 | + while (left < n && on[left]) left++; |
| 61 | + //if the bulbs are on left is equal to current bulbs we trun on. |
| 62 | + //then they all are blue. |
| 63 | + if (left == i+1) result++; |
| 64 | + } |
| 65 | + return result; |
| 66 | + } |
| 67 | +}; |
0 commit comments