3 minutes
Leetcode 1762
1762. Buildings With an Ocean View
The idea of the solution:
The idea of this solution is to loop through the array heights
backwards. Then we just have to find if a height that is greater that the curent height. After that we can reverse the resulting array because the problem asks us to give us the sorted array of indexes that have an ocean view.
If you don’t understand the explaination just look at the following images:
The input:
Since
max = 0
andheights[6] = 1
. Since1 > 0
we add the index6
to the resulting arrayarr
, right nowarr = []
, and if we add6
to it we getarr = [6]
. We also have to makemax = 1
because that is how we know that we can’t see the ocean if it is smaller than or equal tomax
.
Now we are at index
5
. Right now we havemax = 1
, and as we can see3
is greater thanmax
so we can add the index5
toarr
, and makearr = [6, 5]
.
Since
max = 3
andheights[4] = 2
, so we don’t add4
toarr
.
At index
3
and we havemax = 3
. Sinceheights[3] = 4
and4 > 3
we can add the index3
toarr
. So nowarr = [6, 5, 3]
We are at index
2
and we havemax = 4
. Sinceheights[2] = 3
we don’t add2
toarr
because3 < 4
Now we are at index
1
, andheights[1] = 5
whilemax = 4
. Since5 > 4
we add1
toarr
. Nowarr = [6, 5, 3, 1]
.
As we can see at index
0
heights[0] = 2
, whilemax = 5
. Since2 < 5
we don’t add toarr
.
After all of this we get the array arr = [6, 5, 3, 1]
. Now the problem asks us to return the array sorted in a increasing order, so all we have to do is reverse arr
and we get arr = [1, 3, 5, 6]
. Now we can return arr
.
func findBuildings(heights []int) []int {
maximum := 0
arr := []int{}
for i := len(heights) - 1; i >= 0; i-- {
if heights[i] > maximum {
maximum = heights[i]
arr = append(arr, i)
}
}
return reverseArr(arr)
}
func reverseArr(arr []int) []int {
left, right := 0, len(arr)-1
for left < right {
arr[left], arr[right] = arr[right], arr[left]
left, right = left+1, right-1
}
return arr
}