LeetCode
Search…
Wake Up and Solve That LeetCode Problem!
Array
Array
Buildings With an Ocean View
Powered By
GitBook
Buildings With an Ocean View
輸入一個 array,array 中一定會有元素,而每個元素代表大樓高度,array 的最右邊則是海。輸出一個 boolean array,標示該棟大樓是否看得到海(Note: 可能被右邊高的建築,擋到視野)
Example
1
// input example: [6, 3, 4, 1, 2, 1] ~~sea~~
2
3
function
checkIfSeaCanBeSeen
(
arr
){
4
// TODOS
5
}
6
console
.
log
(
checkIfSeaCanBeSeen
([
6
,
3
,
4
,
1
,
2
,
1
]));
7
// [true, false, true, false, true, true]
Copied!
Answer
如果是讓人類用肉眼檢查,可以是站在海上,往大樓方向看去,能看到的大樓就一定可以反過來看得到海。所以可以從 array 的靠海處,也就是由後到前 loop 一次 array,並在過程中記下當前遇到最高的大樓層數,只要當前 loop 到的樓層高於遇到的當前最高樓層,該大樓就一定可以看得到海
1
function
checkIfSeaCanBeSeen
(
array
)
{
2
let
high
=
array
[
array
.
length
-
1
];
3
let
length
=
array
.
length
-
2
;
4
let
newArray
=
[
true
];
5
6
for
(
let
i
=
length
;
i
>=
0
;
i
--
)
{
7
if
(
array
[
i
]
>
high
)
{
8
high
=
array
[
i
];
9
newArray
.
unshift
(
true
);
10
}
else
{
11
newArray
.
unshift
(
false
);
12
}
13
}
14
15
return
newArray
;
16
}
Copied!
Array - Previous
Array
Last modified
1yr ago
Copy link
Contents
Example
Answer