房間中有 n 枚燈泡,編號從 1 到 n,自左向右排成一排。最初,所有的燈都是關着的。
在 k 時刻( k 的取值範圍是 0 到 n - 1),我們打開 light[k] 這個燈。
燈的顏色要想 變成藍色 就必須同時滿足下面兩個條件:
燈處於打開狀態。
排在它之前(左側)的所有燈也都處於打開狀態。
請返回能夠讓 所有開着的 燈都 變成藍色 的時刻 數目 。
示例 1:
輸入:light = [2,1,3,5,4]
輸出:3
解釋:所有開着的燈都變藍的時刻分別是 1,2 和 4 。
示例 2:
輸入:light = [3,2,4,1,5]
輸出:2
解釋:所有開着的燈都變藍的時刻分別是 3 和 4(index-0)。
示例 3:
輸入:light = [4,1,2,3]
輸出:1
解釋:所有開着的燈都變藍的時刻是 3(index-0)。
第 4 個燈在時刻 3 變藍。
示例 4:
輸入:light = [2,1,4,3,6,5]
輸出:3
示例 5:
輸入:light = [1,2,3,4,5,6]
輸出:6
提示:
n == light.length
1 <= n <= 5 * 10^4
light 是 [1, 2, …, n] 的一個排列。
class Solution {
public:
int numTimesAllBlue(vector<int>& light) {
int open[50050]={0};
int n = light.size(), vis = 0, maxn = 0, cur = 0;
for (int i = 0; i < n; ++i) {
open[light[i]] = 1;
maxn=max(maxn,light[i]);
while(open[vis + 1])
vis++;
if(cur == maxn)
cnt++;
}
return cnt;
}
};
超時代碼
class Solution {
public:
int numTimesAllBlue(vector<int>& light) {
int open[50050]={0};
int n = light.size(), cnt = 0, maxn = 0;
for (int i = 0; i < n; ++i) {
open[light[i]] = 1;
int flag = 0;
maxn = max(maxn, light[i]);
for (int j = 1; j <= maxn; ++j)
if (open[j] == 0) {
flag = 1;
break;
}
if (flag == 0)
cnt++;
}
return cnt;
}
};