跳转至

3285. 找到稳定山的下标

题目描述

有 n 座山排成一列,每座山都有一个高度。给你一个整数数组 height ,其中 height[i] 表示第 i 座山的高度,再给你一个整数 threshold 。

对于下标不为 0 的一座山,如果它左侧相邻的山的高度 严格大于 threshold ,那么我们称它是 稳定 的。我们定义下标为 0 的山 不是 稳定的。

请你返回一个数组,包含所有 稳定 山的下标,你可以以 任意 顺序返回下标数组。

 

示例 1:

输入:height = [1,2,3,4,5], threshold = 2

输出:[3,4]

解释:

  • 下标为 3 的山是稳定的,因为 height[2] == 3 大于 threshold == 2 。
  • 下标为 4 的山是稳定的,因为 height[3] == 4 大于 threshold == 2.

示例 2:

输入:height = [10,1,10,1,10], threshold = 3

输出:[1,3]

示例 3:

输入:height = [10,1,10,1,10], threshold = 10

输出:[]

 

提示:

  • 2 <= n == height.length <= 100
  • 1 <= height[i] <= 100
  • 1 <= threshold <= 100

解法

方法一:遍历

我们直接从下标为 \(1\) 的山开始遍历,如果它左侧相邻的山的高度大于 \(threshold\),那么我们就将它的下标加入到结果数组中。

遍历结束后,返回结果数组即可。

时间复杂度 \(O(n)\),其中 \(n\) 是数组 \(\textit{height}\) 的长度。忽略答案数组的空间消耗,空间复杂度 \(O(1)\)

1
2
3
class Solution:
    def stableMountains(self, height: List[int], threshold: int) -> List[int]:
        return [i for i in range(1, len(height)) if height[i - 1] > threshold]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
    public List<Integer> stableMountains(int[] height, int threshold) {
        List<Integer> ans = new ArrayList<>();
        for (int i = 1; i < height.length; ++i) {
            if (height[i - 1] > threshold) {
                ans.add(i);
            }
        }
        return ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
public:
    vector<int> stableMountains(vector<int>& height, int threshold) {
        vector<int> ans;
        for (int i = 1; i < height.size(); ++i) {
            if (height[i - 1] > threshold) {
                ans.push_back(i);
            }
        }
        return ans;
    }
};
1
2
3
4
5
6
7
8
func stableMountains(height []int, threshold int) (ans []int) {
    for i := 1; i < len(height); i++ {
        if height[i-1] > threshold {
            ans = append(ans, i)
        }
    }
    return
}
1
2
3
4
5
6
7
8
9
function stableMountains(height: number[], threshold: number): number[] {
    const ans: number[] = [];
    for (let i = 1; i < height.length; ++i) {
        if (height[i - 1] > threshold) {
            ans.push(i);
        }
    }
    return ans;
}

评论

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy