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 = 0andheights[6] = 1. Since1 > 0we add the index6to the resulting arrayarr, right nowarr = [], and if we add6to it we getarr = [6]. We also have to makemax = 1because 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 see3is greater thanmaxso we can add the index5toarr, and makearr = [6, 5].

Since
max = 3andheights[4] = 2, so we don’t add4toarr.

At index
3and we havemax = 3. Sinceheights[3] = 4and4 > 3we can add the index3toarr. So nowarr = [6, 5, 3]

We are at index
2and we havemax = 4. Sinceheights[2] = 3we don’t add2toarrbecause3 < 4

Now we are at index
1, andheights[1] = 5whilemax = 4. Since5 > 4we add1toarr. Nowarr = [6, 5, 3, 1].

As we can see at index
0heights[0] = 2, whilemax = 5. Since2 < 5we 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
}