Day24:队列的最大值
科技馆内有一台虚拟观景望远镜,它可以用来观测特定纬度地区的地形情况。该纬度的海拔数据记于数组 heights
,其中 heights[i]
表示对应位置的海拔高度。请找出并返回望远镜视野范围 limit
内,可以观测到的最高海拔值。
示例 1:
输入:heights = [14,2,27,-5,28,13,39], limit = 3 输出:[27,27,28,28,39] 解释: 滑动窗口的位置 最大值 --------------- ----- [14 2 27] -5 28 13 39 27 14 [2 27 -5] 28 13 39 27 14 2 [27 -5 28] 13 39 28 14 2 27 [-5 28 13] 39 28 14 2 27 -5 [28 13 39] 39
LCR 183. 望远镜中最高的海拔 - 力扣(LeetCode)
class Solution {
public int[] maxAltitude(int[] heights, int limit) {
if(heights.length == 0 || limit == 0) return new int[0];
Deque<Integer> deque = new LinkedList<>();
int[] res = new int[heights.length - limit + 1];
int index = 0;
for(int i = 0; i < heights.length; i++){
while(!deque.isEmpty() && heights[deque.peekLast()] <= heights[i]){
deque.pollLast();
}
deque.add(i);
if(deque.peekLast() - limit == deque.peek()){
deque.poll();
}
if((i + 1) >= limit){
res[index] = heights[deque.peek()];
index++;
}
}
return res;
}
}
选择用一个双端队列来维护窗口
首先队列里保存的是数组索引,方便比较窗口长度。
然后队头是要维护最大值的,所以如果不大于队头的元素会从队尾出去。
注意一下出队的条件。这个题写过一遍就不难。