【數組】B064_LC_燈泡開關 III(思維題)

一、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,如果當前時刻 ii,達到這個 max,證明這個時刻是存在連續一排藍色燈的。
  • 也就是說當我們打開的燈的位置 max 遠遠大於當前時刻 ii,就不會存在連續的一排藍色燈。
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;
    }
}

複雜度分析

  • 時間複雜度:O(n)O(n)
  • 空間複雜度:O(1)O(1)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章