mirror of
https://github.com/CyC2018/Interview-Notebook.git
synced 2026-10-30 07:33:45 +00:00
Update 59. 滑动窗口的最大值.md
题目链接改为力扣中的对应题目,题目描述和代码按该题的接口调整。
This commit is contained in:
+15
-12
@@ -2,7 +2,7 @@
|
||||
|
||||
## 题目链接
|
||||
|
||||
[牛客网](https://www.nowcoder.com/practice/1624bc35a45c42c0bc17d17fa0cba788?tpId=13&tqId=11217&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
|
||||
[Leetcode](https://leetcode.cn/problems/hua-dong-chuang-kou-de-zui-da-zhi-lcof/)
|
||||
|
||||
## 题目描述
|
||||
|
||||
@@ -19,18 +19,21 @@
|
||||
假设窗口的大小为 M,数组的长度为 N。在窗口向右移动时,需要先在堆中删除离开窗口的元素,并将新到达的元素添加到堆中,这两个操作的时间复杂度都为 log<sub>2</sub>M,因此算法的时间复杂度为 O(Nlog<sub>2</sub>M),空间复杂度为 O(M)。
|
||||
|
||||
```java
|
||||
public ArrayList<Integer> maxInWindows(int[] num, int size) {
|
||||
ArrayList<Integer> ret = new ArrayList<>();
|
||||
if (size > num.length || size < 1)
|
||||
return ret;
|
||||
public int[] maxAltitude(int[] heights, int limit) {
|
||||
if (heights == null || heights.length == 0 || limit <= 0) {
|
||||
return new int[0];
|
||||
}
|
||||
int[] ret = new int[heights.length - limit + 1];
|
||||
PriorityQueue<Integer> heap = new PriorityQueue<>((o1, o2) -> o2 - o1); /* 大顶堆 */
|
||||
for (int i = 0; i < size; i++)
|
||||
heap.add(num[i]);
|
||||
ret.add(heap.peek());
|
||||
for (int i = 0, j = i + size; j < num.length; i++, j++) { /* 维护一个大小为 size 的大顶堆 */
|
||||
heap.remove(num[i]);
|
||||
heap.add(num[j]);
|
||||
ret.add(heap.peek());
|
||||
for (int i = 0; i < limit; i++) {
|
||||
heap.add(heights[i]);
|
||||
}
|
||||
int idx = 0;
|
||||
ret[idx++] = heap.peek();
|
||||
for (int i = 0, j = i + limit; j < heights.length; i++, j++) { /* 维护一个大小为 limit 的大顶堆 */
|
||||
heap.remove(heights[i]);
|
||||
heap.add(heights[j]);
|
||||
ret[idx++] = heap.peek();
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user