【leetcode】-能看到海景的建筑物

332 阅读1分钟

题目

有 n 座建筑物。给你一个大小为 n 的整数组, heights 表示每一个建筑物的高度。建筑物的右边是海洋,如果建筑物可以无障碍地看到海洋,则建筑物能看到海景。

确切地说,如果一座建筑物右边的所有建筑物都比它矮时,就认为它能看到海景。

求:返回能看到海景建筑物的下标列表(下标从 0 开始),并按升序排列。

示例

示例1:
输入:heights = [4,2,3,1]
输出:[0,2,3]
解释:1号建筑物看不到海景,因为2号建筑物比它高
示例2:
输入:heights = [4,3,2,1]
输出:[0,1,2,3]
解释:所有的建筑物都能看到海景
示例3:
输入:heights = [1,3,2,4]
输出:[3]
解释:只有3号建筑物能看到海景
示例4:
输入:heights = [2,2,2,2]
输出:[3]
解释:如果建筑物右边有相同高度的建筑物则无法看到海景

求解

第一种方法

// ◆封装能看到海景的建筑物的函数
function getRes(heights) {
    let max = 0
    let res = []
    for (let i = heights.length - 1; i > -1; i--) {
        let currItem = heights[i]
        if (max < currItem) {
            max = currItem
            res.push(i)
        }
    }
    res = res.reverse()
    return res
}

// ◆测试用例
let heights1 = [9, 8, 7, 1]
console.log(getRes(heights1));
//[ 0, 1, 2, 3 ]
let heights2 = [1, 8, 7, 2]
console.log(getRes(heights2));
//[ 1, 2, 3 ]
let heights3 = [8, 8, 8, 8]
console.log(getRes(heights3));
//[ 3 ]

第二种方法

// ◆封装能看到海景的建筑物的函数
function getSeaIdArr(heights) {
    let seaIdArr = []
    heights.forEach((item, index) => {
        let canSeeSea = true
        for (let i = index + 1; i < heights.length; i++) {
            if (heights[i] >= item) {
                canSeeSea = false
                return
            }
        }
        if (canSeeSea) {
            seaIdArr.push(index)
        }
    })
    return seaIdArr
}
// ◆测试用例
let heights1 = [4, 3, 2, 1]
console.log(getSeaIdArr(heights1));
// [ 0, 1, 2, 3 ]
let heights2 = [1, 2, 4, 1]
console.log(getSeaIdArr(heights2));
// [ 2, 3 ]
let heights3 = [2, 2, 2, 2]
console.log(getSeaIdArr(heights3));
// [ 3 ]